Async/Await — JavaScript

With async and await, you write code that waits for a Promise and still reads from top to bottom. async marks a function that may use await, and that function…

The .then chain (several .then calls in a row) in the Fetch & Promises lesson works well, but it is not easy to read: the result of the first step is passed to the next .then, then to the .then after that. The more steps there are, the longer the chain becomes, and the harder it is to follow.

async and await are another way to write code that waits for a Promise, for example the reply from a server. The result is the same as with a .then chain. The difference is that the code reads from top to bottom like ordinary code: wait for this, then do that.

Wait with await

In the code below, showStudent waits for a student's data with await:

function getStudent(id) {
  return new Promise((resolve) => {
    setTimeout(() => resolve({ id: id, name: 'Budi' }), 800)
  })
}

async function showStudent() {
  console.log('1. ask for the student')
  const student = await getStudent(1)
  console.log('3. got:', student.name)
}

showStudent()
console.log('2. the line after showStudent()')

What prints, in order:

1. ask for the student
2. the line after showStudent()
3. got: Budi

This is the order of events:

  1. showStudent() prints line 1, then pauses at await to wait 800 ms for the Promise from getStudent(1).
  2. While showStudent is paused, the program continues to the line below it, and line 2 prints.
  3. As soon as the Promise finishes, showStudent continues from where it stopped and prints line 3.

So await pauses only its own function, not the whole program.

An async function always returns a Promise

The function greet below waits half a second, then returns some text:

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

async function greet() {
  await delay(500)
  return 'Hello!'
}

greet().then((text) => console.log(text)) // Hello! (half a second later)

Several awaits in a row

One function can hold several awaits. The function introduce below waits for a name, then waits for a city:

async function getName() { return 'Budi' }
async function getCity() { return 'Leeds' }

async function introduce() {
  const name = await getName()
  const city = await getCity()
  return name + ' from ' + city
}

introduce().then((text) => console.log(text)) // Budi from Leeds

Each await waits for one Promise and gives you its result. Only then does the function continue to the next line. So name and city hold the results, not Promises, and can be joined. Without await, getName() + ' from ' + getCity() gives [object Promise] from [object Promise].

Other options. getName and getCity do not depend on each other, so there is no need to wait for them one at a time. In this code, both are called at the same time. Promise.all waits until all of them are done, then gives their results as an array in the same order, [name, city]:

async function introduceFaster() {
  const [name, city] = await Promise.all([getName(), getCity()])
  return name + ' from ' + city
}
Way When to use it
await one at a time The way used in this lesson. Use it when the next step needs the result of the step before.
Promise.all([...]) Requests that do not depend on each other. If one fails, await throws an error at once.
Promise.allSettled([...]) You need every result even if some fail. Each result has a status, "fulfilled" or "rejected".

In other people's code, you will also meet two other ways to ask for data. axios is a library (ready-made code written by other people) that reads JSON by itself and throws an error for replies such as 404. XMLHttpRequest is the older way, from before fetch existed. For new code, fetch is enough.

If a Promise that you await fails, await throws its error. So you can catch that failure with an ordinary try...catch:

async function showStudent() {
  try {
    const student = await getStudent(1)
    console.log('got:', student.name)
  } catch (error) {
    console.log('failed:', error.message)
  }
}

⚠️ When await doesn't wait the way you think

TL;DR: With async and await, you write code that waits for a Promise and still reads from top to bottom. async marks a function that may use await, and that function always returns a Promise. await waits for a Promise, then gives you its value. await pauses only its own function: code outside that function continues to run. Several awaits in a row wait one at a time, and each await gives you its result, not a Promise. If the Promise fails, catch its error with try...catch.

⚡ await pauses only its own function

Write:

async function showStudent() {
  console.log('1. ask for the student')
  const student = await getStudent(1)
  console.log('3. got:', student.name)
}

showStudent()
console.log('2. the line after showStudent()')

Meaning: async marks a function that may use await. showStudent prints line 1, then pauses at await until the Promise from getStudent(1) finishes. During that time the program continues, so line 2 prints before line 3. student holds the resulting object, not a Promise. await can only be written inside an async function, or outside all functions in a module (a file loaded with type="module").

⚡ An async function always returns a Promise

Write:

async function f() {
  return 5
}
Guess first: what does f() give?

A Promise that holds 5, not the number 5. Whatever an async function returns is wrapped in a Promise.

Meaning: An async function always returns a Promise. Get its value with .then, or with await inside another async function.

⚡ Catch failures with try...catch

Write:

try {
  const student = await getStudent(1)
  console.log('got:', student.name)
} catch (error) {
  console.log('failed:', error.message)
}

Meaning: This code is written inside an async function. If a Promise that you await fails, await throws its error. So an ordinary try...catch can catch that error. Without try...catch, the console shows "Uncaught (in promise)" and the rest of the function does not run.

What you will learn