Sub topic 3
Sequential or Parallel: Awaiting Multiple Operations
This chapter assumes you can write async functions, use await, and handle errors with try/catch.
Sequential versus Parallel
Each await waits for one Promise to settle before the next line runs. Independent tasks awaited one after another take the sum of their durations. If you start them together and await Promise.all, the total time is only as long as the slowest task.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function compare() {
console.time('sequential');
await delay(1000, 'a');
await delay(1000, 'b');
console.timeEnd('sequential'); // about 2000 ms
console.time('parallel');
await Promise.all([delay(1000, 'a'), delay(1000, 'b')]);
console.timeEnd('parallel'); // about 1000 ms
}
compare();Run tasks sequentially only when one task needs the result of an earlier one.
Common Mistakes
- Forgotten
await: you get a pending Promise instead of a value, and if it rejects, nothing catches the error. - Async callbacks in
forEach:forEachignores the Promises your callback returns. Usefor...ofto run steps in order, orPromise.all(items.map(...))to run them in parallel.
Microtasks and Execution Order
The code after an await resumes as a microtask. Microtasks run as soon as the current synchronous code finishes, and before timer callbacks.
console.log('A');
setTimeout(() => console.log('E'), 0);
(async () => {
console.log('B');
await null;
console.log('D');
})();
console.log('C');
// A, B, C, D, EAsync Generators
An async function* yields values over time. You consume them with for await...of.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function* countdown(n) {
while (n > 0) {
await delay(100);
yield n--;
}
}
(async () => {
for await (const n of countdown(3)) console.log(n); // 3, 2, 1
})();Top-Level await
You can use await outside any function in an ES module, such as a .mjs file or a <script type="module">. Any module that imports this one waits until the await has settled.
// config.mjs
const config = await Promise.resolve({ debug: true });
console.log(config.debug); // trueCancelling with AbortController
Pass controller.signal to fetch. When you call controller.abort(), the awaited Promise rejects with an AbortError, which you can catch.
async function fetchWithTimeout(url, ms) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const response = await fetch(url, { signal: controller.signal });
return await response.json();
} catch (err) {
if (err.name === 'AbortError') throw new Error(`Timed out after ${ms} ms`);
throw err;
} finally {
clearTimeout(timer);
}
}Exercise
The code ids.forEach(async id => { await save(id); }); console.log('saved'); logs "saved" before any save finishes. Rewrite it so that "saved" is logged after all saves complete, with the saves running in parallel.
Show answer
Inside an async function, write await Promise.all(ids.map(id => save(id))); console.log('saved');.