async-await in Javascript

Async-await is a new feature added in javascript. In async-await, async is async functions and await is an operator.

Why should you care?
Async-await solves the following problems.
1. Callback hell and Chain of Promise.
2. Make you asynchronous code more readable.
3. It can be used to make sure that every bit of data is available before executing some magical instructions.

What is it?
Let’s talk about async first. By using async, you can write asynchronous code as if it is synchronous. It makes your promise based asynchronous code looks and behaves like synchronous, more readable without blocking main execution thread of javascript. Async always returns a Promise if you use await of not.That promise resolves with whatever the async function returns, or rejects with whatever the async function throws.

Now let’s talk about await. Await can be used only inside async functions. It is used to wait for Promise. Await expression contain a value fulfilled by Promise.

How to write it?
Below is the code snippet how to use async and await keyword.

function resolveAfter2Seconds() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(‘resolved’);
}, 2000);
});
}
//function can be decalred as async
async function asyncCall() {
console.log(‘calling’);
/** wait for promise */
const result = await resolveAfter2Seconds();
/** After fulfilled promise execution of function start again from here */
console.log(result);
setTimeout(() => {console.log(“after await”);},1000);
}
asyncCall();
console.log(“test”);
asyncCall();
output:calling // First asyncCall, function execution stop for await
test // It is not blocking the main thread
calling // Second asyncCall, function execution stop for await
resolved // Print fulfilled promise result of asyncCall
resolved // Print fulfilled promise result of asyncCall
after await // Timeout executes of the first asyncCall
after await // Timeout executes of the second asyncCall

As you can see code looks like and execute as synchronous. Execution of function starts again where the code has been left for a wait. Execution of code is asynchronous and non-blocking. Async/await developed using a promise and generator functionality of javascript.

Where to use it?

Suppose you are writing code for showing index page of a book. To show index page, you have following API.
1. Fetch unique id of chapters(getAllChaptersId).
2. Fetch information regarding chapters(getChapterDetail).

You can implement functionality using promise as shown below:

function loadIndexPage(){
fetch("/getAllChaptersId").then((response) => {
return Promise.all(
response.chapters.map((chapterId) => fetch(`/getChapterDetail? id=${chapterId}`));
).then((chapters) => {
chapters.forEach(addTitleToIndex);
}).catch((error) => {
showError("Unable to load");
});
}

You can implement the same functionality using async/await as shown below:

async function loadIndexPage(){
const chaptersId = await fetch("/getAllChaptersId");
const chapters = chaptersId.map( chapterId => {
const response = await fetch(`/getChapterDetail?id=${chapterId}`);
return response;
});
chapters.forEach(addTitleToIndex);
}

As you can see it is more readable and easy to understand. It avoids callback hell and series of then functions.

You can handle errors by following methods.

  1. try…catch block
  2. Add catch block to promise.

Thing to remember

  1. Don’t write code too sequential.
  2. Check for browser support and add polyfill.

Useful resources

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
  2. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
  3. https://developers.google.com/web/fundamentals/primers/async-functions

--

--