Sub topic 5
Pausing with await
This chapter assumes you know how Promises settle (fulfilled or rejected) and that an async function always returns a Promise. The await operator builds directly on both ideas.
What await does
await is an operator you place before an expression inside an async function. When execution reaches it, three things happen:
- The expression is evaluated. If it is not a Promise, it is wrapped in an already-fulfilled one.
- The async function suspends at that point and hands control back to its caller.
- When the Promise fulfills, the function resumes, and the
awaitexpression evaluates to the fulfilled value.
Only the async function pauses. The rest of the program keeps running.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function main() {
console.log('start');
const result = await delay(1000, 'done');
console.log(result); // 'done' after about 1 second
}
main();
console.log('main() returned, program keeps going');The output is:
// start
// main() returned, program keeps going
// donemain() runs synchronously until the first await. Then it returns its pending Promise to the caller, and the last console.log runs. About one second later the timer fires, the Promise fulfills, and main picks up where it left off.
await compared with then
await does the same job as .then(), written as straight-line code. These two functions behave the same:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
function withThen() {
return delay(500, 2).then(n => n * 10);
}
async function withAwait() {
const n = await delay(500, 2);
return n * 10;
}
withThen().then(console.log); // 20
withAwait().then(console.log); // 20With await, every later step can use earlier values as ordinary local variables. You don't need nested callbacks or values passed down a chain.
Awaiting non-Promise values
You can await any value. await 42 evaluates to 42, but the function still suspends briefly before continuing. This means await always splits a function into a "before" part and an "after" part, even when nothing is actually slow. The chapter on microtasks explains exactly when the "after" part runs.
Where await is allowed
await works inside async functions. In a regular function it causes a SyntaxError:
function broken() {
const value = await Promise.resolve(1); // SyntaxError
}The fix is to mark the function async. This applies to callbacks too: items.map(async item => await work(item)) is valid. ES modules also allow await at the top level, which a later chapter covers.
When the Promise rejects
If the awaited Promise rejects, await throws the rejection reason at that line, as if a throw statement were there. The code after it in the function doesn't run, and the function's own Promise rejects. The next chapter shows how to handle this with try/catch/finally.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError` mentioning `await` | `await` used in a non-async function | Add `async` to the enclosing function |
| Variable holds `Promise { <pending> }` | Missing `await` | Await the call |
| Code after the async call runs "too early" | Caller didn't await the async function | Await it, or use `.then()` on its result |
Exercise
What does this code print, and in what order? async function f() { console.log(1); const x = await 5; console.log(x); } f(); console.log(2);
Show answer
It prints 1, 2, 5. The function runs synchronously until the await, which suspends it even though 5 is not a Promise. Control returns to the caller, which prints 2, and then f resumes and prints 5.
Exercise
A teammate writes async function getTotal() { const prices = fetchPrices(); return prices.reduce((a, b) => a + b, 0); }, where fetchPrices returns a Promise of an array. Why does it fail, and how do you fix it?
Show answer
Without await, prices is a Promise, and Promises have no reduce method, so the call throws a TypeError. Write const prices = await fetchPrices(); so prices holds the fulfilled array.