Sub topic 2
Pausing with await
This chapter assumes you know what a Promise is and that an async function always returns one. It also assumes you are comfortable with try/catch/finally.
Pausing with await
The await operator suspends the surrounding async function until a Promise settles. It then evaluates to the fulfilled value. Only that 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();A common error is forgetting await. Without it, result holds the Promise itself instead of 'done'.
Handling Errors with try/catch/finally
If an awaited Promise rejects, the await expression throws. That lets ordinary try/catch/finally handle the failure. Note that fetch only rejects on network failures. An HTTP 404 still fulfills, so you must check response.ok yourself.
async function loadUser(id) {
try {
const response = await fetch(`https://api.example.com/users/${id}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (err) {
console.error('Failed to load user:', err);
throw err;
} finally {
console.log('loadUser finished');
}
}If you rethrow in catch, the caller's Promise rejects too. If you swallow the error without rethrowing, the caller receives undefined.
Combining Promises: all, allSettled, race, and any
When you have several Promises, a combinator turns them into one Promise that you can await.
| Combinator | Fulfills when | Rejects when |
|---|---|---|
| `Promise.all` | every input fulfills (array of values) | the first input rejects |
| `Promise.allSettled` | every input settles (array of outcomes) | never |
| `Promise.race` | the first input settles, if it fulfills | the first input settles, if it rejects |
| `Promise.any` | the first input fulfills | every input rejects (`AggregateError`) |
Promise.allSettled keeps every result even when some inputs fail:
async function loadAll() {
const results = await Promise.allSettled([
Promise.resolve('ok'),
Promise.reject(new Error('failed'))
]);
for (const r of results) {
if (r.status === 'fulfilled') {
console.log('value:', r.value);
} else {
console.log('reason:', r.reason.message);
}
}
}
loadAll(); // value: ok, then reason: failedExercise
You query three mirror servers and want the first successful response, ignoring servers that fail. Which combinator do you use, and what happens if all three fail?
Show answer
Use Promise.any. It fulfills with the first successful response. If all three reject, it rejects with an AggregateError that holds every reason.