Generally, when we’re told to handle async code, we’re often redirected to promises. However, there is another way of handling async code called async await.
Lets use the example many use when teaching new developers how promises work
const examplePromise = new Promise((resolve,reject) => {
setTimeout(() => resolve('ourResolvedData'), 3000);
});
This is an example of a promise created by us using set Timeout.
The promises way of resolving this would be
const finalValue = examplePromise.then(result => result);
When we console.log that result, we get
Promise {<resolved>: "ourResolvedData"}
This doesn’t help us much so lets adjust it:
let finalValue;
examplePromise.then(result => a = result);
Promise chains can get messed as you continue to chain them. An alternative solution is async await:
To start using async await first we need to add the word async onto a function letting it know that its an async/await function
async function exampleAsync() {
}
Next let’s call our examplePromise function. Inside our async function. Instead of chaining a then onto it, lets put the word async
in front of it:
async function exampleAsync() {
const response = await examplePromise;
}
Lets add a console log inside our exampleAsync function and see what we get back:
async function exampleAsync() {
const response = await examplePromise;
console.log(response);
}
Note that the console.log returned ourResolvedData
instead of Promise {<resolved>: "ourResolvedData"}
Note that if you want to use async await, you must create an async function. You cannot call await in the global scope or in a function that is isn’t marked as async.
We can also use async await with arrow functions:
const exampleAsync2 = async () => {
const response = await examplePromise;
console.log(response);
}