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:
showStudent()prints line 1, then pauses atawaitto wait 800 ms for the Promise fromgetStudent(1).- While
showStudentis paused, the program continues to the line below it, and line 2 prints. - As soon as the Promise finishes,
showStudentcontinues from where it stopped and prints line 3.
So await pauses only its own function, not the whole program.
getStudent(1)returns a Promise that finishes 800 ms later, likefetchwaiting for a server's reply.asyncin front offunctionmarks a function that is allowed to useawait.await getStudent(1)waits for that Promise to finish, then gives you its value. Sostudentholds the object{ id: 1, name: 'Budi' }, not a Promise.awaitcan only be written inside anasyncfunction, or outside all functions in a module (a JavaScript file loaded with<script type="module">). For example,function getData() { const data = await fetch(url) }is an error, because there is noasyncin front of it.
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)
delay(ms)makes a Promise that finishes aftermsmilliseconds:setTimeoutcallsresolvewhen the pause is over.await delay(500)pausesgreetfor half a second. Withoutawait,delay(500)is only called and not waited for, and'Hello!'is returned immediately.- Whatever an
asyncfunction returns is wrapped in a Promise. For example,async function f() { return 5 }gives a Promise that holds5, not the number5. That is whygreet()above is followed by.then. Get the value of anasyncfunction with.then, or withawaitinside anotherasyncfunction.
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
- Without
await,const data = fetch(url)puts a Promise indata, sodata.nameisundefined. forEachdoes not wait for theasyncfunction inside it. If the work must happen one item at a time, usefor...of.- A failed Promise that no
try...catchcatches appears in the console as "Uncaught (in promise)", and the rest of the function does not run.
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.