Sub topic 3
Sequential Loops versus Concurrent Work
This chapter assumes you know for await...of, async generators, return() cleanup, and Promise.all.
Sequential by design
for await...of waits for each value before it asks for the next one. That order is what you want when each step depends on the previous one, or when you need to limit load on a server. When the tasks are independent, waiting inside a loop wastes time.
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function sequential() {
const results = [];
for (const ms of [300, 200, 100]) {
results.push(await sleep(ms, ms)); // about 600 ms total
}
return results;
}
async function concurrent() {
// all timers start at once, about 300 ms total
return Promise.all([300, 200, 100].map((ms) => sleep(ms, ms)));
}Promise.all rejects as soon as any task fails. Use Promise.allSettled if you need every outcome.
| Workload | Choose |
|---|---|
| Unbounded or streaming source | `for await...of` |
| Fixed set of independent tasks | `Promise.all` |
| Order or rate limits matter | `for await...of` |
Streams and readline
Node.js readable streams, readline interfaces, and web ReadableStream objects are already async iterable. In an ES module you can loop over them with top-level await:
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
const rl = createInterface({
input: createReadStream('data.txt'),
crlfDelay: Infinity
});
let lineCount = 0;
for await (const line of rl) {
lineCount++;
}
console.log(`Lines: ${lineCount}`);If you break out of the loop, the stream is closed for you.
Delegating with yield*
Inside an async function*, yield* source yields every value from another iterable, whether it is sync or async. Use it to flatten a page of results into single items.
Pipelines
Each generator below pulls values from the one before it, so work only happens when the consumer asks for the next item.
// Assumes an API that returns { items: [...], nextUrl: string | null }
async function* fetchItems(url) {
let next = url;
while (next) {
const res = await fetch(next);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = await res.json();
yield* body.items;
next = body.nextUrl;
}
}
async function* filter(source, predicate) {
for await (const item of source) {
if (predicate(item)) yield item;
}
}
async function* take(source, limit) {
if (limit <= 0) return;
let count = 0;
for await (const item of source) {
yield item;
if (++count >= limit) return;
}
}
async function main() {
const active = filter(fetchItems('https://example.com/api/items'), (i) => i.active);
for await (const item of take(active, 10)) {
console.log(item);
}
}Array.fromAsync
Array.fromAsync collects an async iterable into an array. It needs Node.js 22 or a current browser. You can pass a mapping function as the second argument.
async function* numbers() {
yield 1;
yield 2;
yield 3;
}
const doubled = await Array.fromAsync(numbers(), (n) => n * 2);
console.log(doubled); // [2, 4, 6]Exercise
In the pipeline, why does fetchItems stop requesting pages after take() has yielded 10 items?
Show answer
When take() returns, its for await...of loop exits and calls return() on filter. That ends filter's loop, which calls return() on fetchItems, so the fetchItems generator finishes before it can request another page.
Exercise
Five independent API calls each take about 1 second. Roughly how long does awaiting them one by one in a loop take, compared with using Promise.all?
Show answer
The loop takes about 5 seconds because each call waits for the one before it. Promise.all takes about 1 second because all five calls run at the same time.