Sub topic 5
Pausing with await
This chapter assumes you already know three things from earlier chapters. You know what a Promise is and its three states. You know how .then() chains work. You also know that an async function always returns a Promise. Here we look at the other half of the pair: the await operator. It pauses an async function until a Promise settles, then hands you the result.
What await does
await is an operator that takes one operand, usually a Promise. When execution reaches await promise, three things happen:
- The async function suspends. Its local variables and its position in the code are saved.
- Control returns to whoever called the function. For the first
await, the caller receives the function's pending Promise. - When the Promise settles, the function resumes at the same spot. If the Promise fulfilled, the
awaitexpression evaluates to the fulfilled value. If it rejected, theawaitexpression throws the rejection reason.
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();Read top to bottom, this looks like blocking code: print, wait, print. It does not block, though. Only main waits. The JavaScript thread is free to do other work in the meantime.
Proving the program is not blocked
The next example runs a ticker while main is suspended. If await blocked the thread, no ticks could print during the wait.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function main() {
console.log('main: start');
const result = await delay(1000, 'done');
console.log('main:', result);
}
main();
console.log('after main() call');
const ticker = setInterval(() => console.log('tick'), 300);
setTimeout(() => clearInterval(ticker), 1100);
// Output:
// main: start
// after main() call
// tick
// tick
// tick
// main: donemain: start prints first, because an async function runs synchronously up to its first await. Next, main() returns, and after main() call prints. The three ticks fire at about 300, 600, and 900 ms while main is parked. At 1000 ms the delay Promise fulfills and main finishes.
await is sugar over then
Anything you write with await you could also write with .then(). The code after an await is, in effect, the callback you would have passed to .then(). These two functions behave the same way:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
function loadWithThen() {
return delay(100, 2)
.then(n => delay(100, n * 10))
.then(m => m + 1);
}
async function loadWithAwait() {
const n = await delay(100, 2);
const m = await delay(100, n * 10);
return m + 1;
}
loadWithThen().then(v => console.log('then:', v)); // then: 21
loadWithAwait().then(v => console.log('await:', v)); // await: 21The await version has some practical advantages:
- Intermediate values (
n,m) are plain variables in one scope. You don't have to nest callbacks or pass values down the chain. - Ordinary control flow works across asynchronous steps. You can use
if,for,while,return, andtry/catchwithout any special Promise API. - Stack traces and debugger stepping follow the source order more closely.
What you can await
The operand of await doesn't have to be a native Promise. The rule: await passes the value through Promise.resolve() and waits for the result.
| Operand | What await evaluates to |
|---|---|
| A fulfilled or pending Promise that fulfills | The fulfilled value |
| A Promise that rejects | Nothing. It throws the rejection reason |
| A thenable (any object with a `then` method) | Whatever the thenable resolves with |
| A plain value such as `5`, `'x'`, `null` | The value itself, after a short asynchronous pause |
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
const thenable = {
then(resolve) {
setTimeout(() => resolve('from thenable'), 100);
}
};
async function demo() {
const a = await 5;
console.log(a); // 5
const b = await thenable;
console.log(b); // 'from thenable'
const c = await delay(100).then(() => 'from promise');
console.log(c); // 'from promise'
}
demo();Thenable support is how await works with older Promise libraries and other custom objects that follow the Promise protocol.
Awaiting a plain value still yields
await 5 returns 5, but not right away. The function still suspends, and the rest of it runs after the current synchronous code finishes:
async function f() {
console.log('1');
await 'x';
console.log('3');
}
f();
console.log('2');
// Output: 1, 2, 3So await always splits a function into a "before" part and an "after" part, even when there is nothing to wait for. The exact scheduling (microtasks versus timers) comes up in a later chapter. For now, remember that code after an await never runs synchronously.
When the awaited Promise rejects
If the Promise rejects, await throws at that line, as if a throw statement were sitting there. Lines after it in the same block don't run. The async function's own Promise then rejects with that reason, unless something catches the error.
async function failing() {
const value = await Promise.reject(new Error('boom'));
console.log('never printed', value);
}
failing().catch(err => console.log('caught:', err.message)); // caught: boomThe next chapter covers handling errors with try/catch/finally in full. The key idea here is that rejection becomes an ordinary exception at the await expression.
Where await is allowed
await is only valid in certain places:
- Inside an
async functiondeclaration or expression. - Inside an
asyncarrow function:async () => { await x; }. - Inside an
asyncmethod in a class or object literal. - At the top level of an ES module. A later chapter covers this.
Everywhere else, await is a SyntaxError. That includes regular functions, non-async callbacks nested inside an async function, and the top level of a CommonJS script. The nesting case catches people out:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function doubleAll(values) {
// SyntaxError if uncommented: the arrow callback is not async,
// even though doubleAll is.
// const bad = values.map(v => await delay(10, v * 2));
const results = [];
for (const v of values) {
results.push(await delay(10, v * 2)); // fine: directly inside doubleAll
}
return results;
}
doubleAll([1, 2, 3]).then(r => console.log(r)); // [ 2, 4, 6 ]await belongs to the nearest enclosing function. Being inside an async function somewhere up the nesting doesn't count. Marking the inner callback async makes the syntax legal, but the callback then returns a Promise, and map or forEach won't wait for it. The chapter on common mistakes covers that trap.
Common errors
Forgetting await
If you leave out await, you get the Promise instead of its value. JavaScript doesn't warn you. You just get wrong data:
async function getUser() {
return { name: 'Ada' };
}
async function main() {
const user = getUser(); // missing await
console.log(user.name); // undefined: user is a Promise
console.log(user instanceof Promise); // true
const realUser = await getUser();
console.log(realUser.name); // Ada
}
main();Signs of a missing await: values print as Promise { <pending> }, properties come back undefined, conditions like if (await isAllowed()) silently become if (promise), which is always truthy, and rejections show up as "unhandled rejection" warnings instead of being caught.
Assuming nothing changes between awaits
Each await is a suspension point. While your function is paused, other code can run and change shared state. A value you read before the await may be stale when you resume:
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
let balance = 100;
async function withdraw(amount) {
const current = balance; // read
await delay(50); // other code runs here
balance = current - amount; // write based on a stale read
}
async function main() {
const first = withdraw(30);
const second = withdraw(50);
await first;
await second;
console.log(balance); // 50, not 20
}
main();Both calls read 100 before either one writes. The fix is to keep the read and the write in the same synchronous stretch, with no await between them, or to serialize the operations. JavaScript is single-threaded, so code between two awaits can't be interrupted. Code that spans an await can.
Awaiting in sequence by accident
Every await waits for its Promise before the next line starts. That is what you want when step two needs the result of step one. When the operations are independent, writing them as back-to-back awaits adds their durations together. A later chapter shows how to measure this and how to start the operations together.
Summary
awaitsuspends the enclosing async function, not the program, and resumes it when the operand settles.- It evaluates to the fulfilled value, or throws the rejection reason.
- It accepts Promises, thenables, and plain values. The code after it always runs asynchronously.
- It is legal only directly inside async functions and at the top level of ES modules.
- Forgotten
awaits and stale state acrossawaits are the most common bugs.
Exercise
What does this program print, and in what order? async function run() { console.log('A'); const x = await 10; console.log('C', x); } run(); console.log('B');
Show answer
It prints A, then B, then C 10. run executes synchronously until its first await, so A prints first. Even awaiting a plain value suspends the function, so run returns and B prints. The function then resumes, and x is 10.
Exercise
A colleague writes async function isAdmin(user) { return user.role === 'admin'; } and then if (isAdmin(guest)) { grantAccess(); } inside an async function. Every guest gets access. Why, and what is the fix?
Show answer
isAdmin is async, so it returns a Promise, and any Promise object is truthy. The if condition is always true, whatever role the user has. The fix is to await the result: if (await isAdmin(guest)) { grantAccess(); }. Another option is to make isAdmin a regular function, since it does no asynchronous work.
Exercise
Rewrite this with await, keeping the same behavior: function total() { return getPrice().then(p => getTax(p).then(t => p + t)); }
Show answer
async function total() { const p = await getPrice(); const t = await getTax(p); return p + t; }. Both versions return a Promise that fulfills with p + t, and both reject if either call rejects. The await version keeps p in scope without nesting the callbacks.