DEV Community

Reza Bozorgi
Reza Bozorgi

Posted on

2 1

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay