How to Use async and await in JavaScript

Writing asynchronous code that reads like synchronous code.

When writing JavaScript your code will often have to wait for something, like data from an API or a file being read. Promises handle this, but a few .then() calls in a row can get hard to follow. async and await let you write the same code in a way that reads top to bottom.

await pauses an async function until a promise resolves, then gives you its value.

From .then() to await

Here's a typical fetch using promises:

function getUser() {
return fetch("https://api.github.com/users/octocat")
.then((response) => response.json())
.then((user) => {
console.log(user.name)
return user
})
}

And here's the same thing with async and await:

async function getUser() {
const response = await fetch("https://api.github.com/users/octocat")
const user = await response.json()
console.log(user.name)
return user
}

Each await waits for its promise to finish before moving on to the next line, so there are no callbacks to nest or chain.

async Functions Always Return a Promise

Adding async in front of a function means it always returns a promise, even if you return a plain value:

async function getNumber() {
return 42
}
getNumber().then((number) => console.log(number)) // 42

This also means you can only use await inside an async function. Using it anywhere else is a syntax error. Arrow functions and methods can be async too:

const getUser = async (username) => {
const response = await fetch(`https://api.github.com/users/${username}`)
return response.json()
}

Handling Errors

With promises you catch errors with .catch(). With await you use a regular try...catch block:

async function getUser(username) {
try {
const response = await fetch(`https://api.github.com/users/${username}`)
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`)
}
return await response.json()
} catch (error) {
console.error(error.message)
}
}

If any await inside the try block rejects, the code jumps straight to the catch block. Note that fetch only rejects on network errors, so checking response.ok lets you treat a 404 as an error too.

Waiting for Things in Order

await inside a loop runs each step one after the other:

async function getUsers(usernames) {
const users = []
for (const username of usernames) {
const user = await getUser(username)
users.push(user)
}
return users
}

This is what you want when each request depends on the one before it. If they don't depend on each other, waiting on them one at a time is slower than it needs to be.

Running Things at the Same Time

To start every request at once and wait for all of them, combine map with Promise.all:

async function getUsers(usernames) {
return Promise.all(usernames.map((username) => getUser(username)))
}
getUsers(["octocat", "gaearon"]).then((users) => console.log(users))

map kicks off every request right away and Promise.all waits until they've all finished. Since await only works inside an async function, the last line uses .then() to read the result.

Have some feedback on this post? .