await
- Node.js course
- Beginner
- Lesson 95/116
- 5 min
Learn to await a promise.
What is await?
await is an operator that waits for a Promise and yields its value. It can only be used inside async functions (or at the top level of a module). When await is hit, the function does not block; it returns to the event loop and resumes when the result arrives.
async function load() {
const value = await Promise.resolve("ok");
console.log(value);
}Here await waits for Promise.resolve("ok") and assigns its result to value. This is more readable than a chained then; you write async code as if it were synchronous.
Practice Your turn: get a value with await
Define async function load(). Inside, write const value = await Promise.resolve("hello"). Log the value with console.log(value). Finally call load().
Starter code
// Define async function load
// Get the value with await Promise.resolve, log with console.log
// Finally call loadSample solution
async function load() {
const value = await Promise.resolve("hello");
console.log(value);
}
load();Expected output
hello
await vs then
await and then do the same job differently. then builds a chain to process the result, while await assigns the result to a variable, letting you write code that looks synchronous. Neither blocks the event loop; both just suspend the waiting function.
// with then
p.then(v => console.log(v));
// with await
const v = await p;
console.log(v);In most cases await is more readable; especially with several dependent async steps, a then chain can get nested. With await you write the same logic as a flat flow.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: await
async function load() {
const value = ____ Promise.resolve("ok");
console.log(value);
}
async function load() {
const value = await Promise.resolve("ok");
console.log(value);
}
Explanation: await assigns the Promise result to value.
2 Where can await NOT be used directly?
- Inside an async function
- Inside a regular function Correct answer
- At the top level of a module
- Inside an async arrow function
Explanation: await only works inside an async context.
3 await vs then
| Term | Meaning |
|---|---|
await |
assigns value to variable |
then |
builds a chain |
async |
required for await |