Async/Await in Asynchronous Javascript

Sherlynn
3 min readDec 29, 2019

To handle asynchronous Javascript, callbacks were first used but it had major cons like callback hell. Then came about promises to try to improve things. However, .then chains can also get nested and confusing.
So now, we have async/await, which was introduced in NodeJS 7.6 and is currently supported in all modern browsers.

The async/await syntax allows you to work with promises in a cleaner fashion. It makes asynchronous code easier to read and understand. However, it is important to note that async/await is actually just syntax sugar built on top of promises. It cannot be used with plain callbacks or node callbacks.

Async/await is similar to promises in that they are non-blocking (since they built on top of promises) and it makes asynchronous code look and behave a more like synchronous code. This is an important advantage over pure promises.

Async

Using the word “async” before a function means that the function will always return a promise. Return values are wrapped in a promise automatically.

For example, this function returns a resolved promise with the result of hello, as shown below:

async function asyncFn() {
return "I love 🍰";
}

asyncFn().then(alert); // I love 🍰
Alert message when executing the code block above in the google chrome console

…or we can also explicitly return a promise, that would produce a similar result:

async function asyncFn() {
return Promise.resolve("I love 🍰");
}

asyncFn().then(alert); // I love 🍰

So, async ensures that the function always returns a promise and hence we can use the .then() method to display the alert output as hello.

Await

Await works only inside async functions.

await will not work in top-level code. For example, this will not work:

// syntax error in top-level codelet response = await fetch('/users.json'); 
let users = await response.json();

To make it work, we can wrap it into an Immediately-invoked Function Expression

Sherlynn

Recommended from Medium

Lists

See more recommendations