DEV Community

Reza Bozorgi
Reza Bozorgi

Posted on

Async/Await in JavaScript

Async functions are brought to JavaScript by ES8 (ES2017) and are used to facilitate the management of asynchronous operations. Async functions use Promises under their own skin.

To use this feature to manage an asynchronous operation, we first use the async keyword when defining a function. We always write the word async at the beginning of the function definition:

const users = async () =>{ }
Enter fullscreen mode Exit fullscreen mode

When we use async, we have another keyword called await. When the await keyword is at the beginning of a expression, our code waits for the output of that expression to be specified and then goes to the next lines. We use await as follows:

const users = async () => {
     let users = await getUsers();
     console.log(users);
}
Enter fullscreen mode Exit fullscreen mode

One thing to keep in mind is that the await keyword should only be used within a function that uses the async keyword at the beginning. Otherwise we get an error.

The next point to keep in mind is that if the expression in front of the await is not a Promise, it will automatically become a resolved Promise when it is done.

The output of an async function is always a Promise and we can treat it like a Promise.

const users = async () =>{
   let users = await getUsers();
   return users;
}

users.then(console.log); //list of users
Enter fullscreen mode Exit fullscreen mode

P.S.: Async code is simpler and more readable than the Promises we had to use with chain methods.

Top comments (0)