How to Wait for a Promise to Resolve
Async
We can start off by looking at the special keyword async that can be placed before a function. This function will operate a function asynchronously via the event loop using an implicit Promise to return its result. If you need a refresher on the event loop checkout out this really amazing video on it! An async function simply implies that a promise will be returned and if a promise is not returned, JavaScript will automatically wrap it in a resolved promise with the return value in that function. That would look like writing return Promise.resolve('hello'). You can write an async function simply by placing the async keyword in front of the function you are creating.
You can see above that running the code give you the output of a promise along with the value that is returned in the async function. You can also explicitly return a promise which would be the same as written below.
async function foo() {
return Promise.resolved('hello');
} foo().then(alert); // hello
Cool so the async keyword allows us to write a function that returns a promise, and wraps a non-promises in it.
Await
The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result. Here is an example with a promise that resolves in 2 seconds.
This is a more elegant way of getting a promise result than using promise.then. We can now turn a function that would just be utilizing the fetch keyword into an async function and see how it differs in clarity.
function jsonData(url) {
return fetch(url)
.then(res => {
if (res.status == 200) {
return res.json();
} else {
throw new Error(res.status);
}
});
}jsonData('non') /
.catch(alert); // Error: 404
This can be updated to the following async function using await.
async function jsonData(url) { // (1)
let res = await fetch(url); // (2) if (res.status == 200) {
let json = await res.json(); // (3)
return json;
}
throw new Error(res.status);
}
jsonData('no-such-user.json')
.catch(alert); // Error: 404 (4)
Important to Note
You cannot use the await keyword inside a regular function. This will cause a syntax error. Await needs to be used only inside an async function.
Although we can now make our code look synchronous, it is important to keep in mind that the execution is still asynchronous! This is important to note because you can dramatically increase your execution time if used incorrectly. The two examples below display the correct way to utilize an async function. If we use await on each individual function, the JavaScript compiler will wait till the first function is resolved prior to executing the second function. The whole point of the event loop is to avoid blocking code like what is done in the first example. If we need to wait for multiple promises we can wrap them in a Promise.all and then use await prior to the promise keyword.
// This would be the bad way to do this as you are blocking b from running until the a function returns.
const makeSomething = async() => {
const a = await getSomething('apples')
const b = await getSomething('strawberry')
return [a, b]
} // This is how you would allow your functions to run simultaneously
const makeSomething = async() => {
const a = getSomething('apples')
const b = getSomething('strawberry')
const result = await Promise.all([a, b]) return result;
} // wrapping our fetch in a Promise.all would allow them to run concurrently.
let results = await Promise.all([
fetch(url1),
fetch(url2),
]);
Conclusion
Async / await allows us to write asynchronous code that reads like synchronous code. It allows for some nicer readability when working with promises! To recap inside a function marked as async, you are allowed to place the await keyword in front of an expression that returns a promise. When you do, the execution of the async function is paused until the promise is resolved.
References
Please checkout all of the material that was reviewed to write this blog. There is a lot of great material to learn more about this nice syntactic sugar approach to promises and asynchronous JavaScript.
How to Wait for a Promise to Resolve
Source: https://itnext.io/async-and-await-in-javascript-the-extension-to-a-promise-f4e0048964ac