Advertisement
728x90
The asynchronous thunks are useful to make network requests. Let's see an example of network requests,
javascript
1function fetchData(fn) {
2 fetch("https://jsonplaceholder.typicode.com/todos/1")
3 .then((response) => response.json())
4 .then((json) => fn(json));
5 }
6
7const asyncThunk = function () {
8 return fetchData(function getData(data) {
9 console.log(data);
10 });
11};
12
13asyncThunk();The getData function won't be called immediately but it will be invoked only when the data is available from API endpoint. The setTimeout function is also used to make our code asynchronous. The best real time example is redux state management library which uses the asynchronous thunks to delay the actions to dispatch.
Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 12
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
355of476