When we need to use third party API or any REST API in our web app, we need to wait for the response coming from the server. Then in the success callback , we use that data and do other operations.And if we have more REST calls, we all know that it could end up being a Callback Hell
But if we use ES2017 async/await syntax , we can write our code as clean as possible with minimum lines of code.
Basic example of async/await is like below-
function resolveAfter2Seconds() {
return new Promise(resolve => {
setTimeout(() => {
resolve('resolved');
}, 2000);
});
}
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
console.log(result);
// expected output: "resolved"
}
asyncCall();
here var result = await resolveAfter2Seconds(); will wait to resolve the Promise and assign the returned data to result
variable.
It seems like its executing the code line by line though it has asynchronous operation , which is awesome!
As of now , we know basic of async/wait , now we will use this inside redux ActionCreator. But first we will see how the code looks like without using async/await. So our action creator code is –
export const getSpeakers = () => (dispatch, getState) => {
return fetch(`${API_SERVER}/speakers`)
.then(
response => response.json(),
error => {
console.log("No! error occured.", error);
throw error;
}
)
.then(speakers => {
console.log("speakers success", speakers);
dispatch(saveSpeakers(speakers));
})
.catch(error => {
console.log("Return Error by throwing", error);
throw error;
});
};
So here ^ is our action creator named getSpeakers
which calls one REST API endpoint and then dispatch the speakers to the redux store.Here we can see we need to chain with then
, catch
etc which make the code a bit messy and hard to understand.
Now we will use async/await with fetch and will make our code good looking
export const getSpeakers = () => async (dispatch, getState) => {
try {
const response = await fetch(`${API_SERVER}/speakers`);
const speakers = await response.json();
console.log("speakers success", speakers);
dispatch(saveSpeakers(speakers));
} catch (error) {
console.log("throwing Error", error);
throw error;
}
};
Here , we have added try/catch so that if any error happens, we can catch and take our decision what we want to do. Here in this case , I have just thrown the error, but we can dispatch another FAILURE action. Ah , that made our code smaller,cleaner and easy to understand!
Cheers!