Sub topic 13
Collecting Async Results with Array.fromAsync
This chapter assumes you know async generators, for await...of, and how early exit calls return(). Those topics are covered in earlier chapters. You also need Node.js 22 or later, or a current browser, because Array.fromAsync is a fairly recent addition to the language.
Sometimes you don't want to process values one at a time. You want all of them in an array, for example to sort them, count them, or send them as one JSON response. Array.fromAsync does that job. It is the async version of Array.from.
The Manual Version
Without Array.fromAsync, you write the collection loop yourself:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* countdown(from) {
for (let i = from; i > 0; i--) {
await sleep(100);
yield i;
}
}
async function collect(source) {
const results = [];
for await (const value of source) {
results.push(value);
}
return results;
}
async function main() {
console.log(await collect(countdown(3))); // [ 3, 2, 1 ]
}
main();This loop shows up in many codebases. Array.fromAsync puts it in one call.
The Built-in Version
Array.fromAsync(items, mapFn, thisArg) returns a Promise that resolves to an array. The mapFn and thisArg arguments are optional.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* countdown(from) {
for (let i = from; i > 0; i--) {
await sleep(100);
yield i;
}
}
async function main() {
const values = await Array.fromAsync(countdown(3));
console.log(values); // [ 3, 2, 1 ]
const doubled = await Array.fromAsync(countdown(3), async (n) => {
await sleep(50);
return n * 2;
});
console.log(doubled); // [ 6, 4, 2 ]
}
main();The mapping function can be async. Array.fromAsync awaits its result before it stores the value and before it asks the source for the next one.
What It Accepts
| Input | How values are read |
|---|---|
| Async iterable (async generator, readline interface) | Through `Symbol.asyncIterator`, awaiting each `next()` |
| Sync iterable (array, Set, sync generator) | Through `Symbol.iterator`, awaiting each value |
| Array-like (`{ length: 2, 0: 'a', 1: 'b' }`) | By index, awaiting each value |
Because each value is awaited, an array of promises works too:
async function main() {
const values = await Array.fromAsync([
Promise.resolve('a'),
'b',
Promise.resolve('c')
]);
console.log(values); // [ 'a', 'b', 'c' ]
}
main();Common Mistakes
Expecting concurrency
Array.fromAsync is sequential, like for await...of. It does not start the next item until the current one settles. If you already have an array of promises that are all running, Promise.all gives the same values and also rejects as soon as any one fails. Array.fromAsync awaits the promises in order. Use it when the source itself produces values over time.
Collecting an endless source
The returned promise resolves only when the source reports done: true. A ticker, a websocket feed, or an infinite generator will never finish, so the promise stays pending forever. Limit the source first. The take() generator from the pipelines chapter does this:
async function* naturals() {
let n = 1;
while (true) yield n++;
}
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() {
console.log(await Array.fromAsync(take(naturals(), 5))); // [ 1, 2, 3, 4, 5 ]
}
main();Forgetting that errors reject
If the source throws or the mapping function throws, the returned promise rejects and any values collected so far are lost. When the error comes from mapFn, Array.fromAsync closes the source iterator, so a generator's finally block still runs. To catch the error, wrap the await in try/catch, the same way you would handle a rejection from any other async call.
Exercise
An async generator yields 1, 2, then throws an Error. What does await Array.fromAsync(gen()) produce, and how do you keep the values 1 and 2?
Show answer
The promise rejects with the error, and the partial array [1, 2] is discarded. To keep partial results, use a manual for await...of loop that pushes into an array declared outside a try/catch. After the catch, the array still holds 1 and 2.
Exercise
You have const urls = [...] and want the parsed JSON of each response as fast as possible. Should you use Array.fromAsync(urls, async (u) => (await fetch(u)).json()) or Promise.all(urls.map(...))?
Show answer
Use Promise.all. Array.fromAsync runs the mapping function one URL at a time, so the total time is the sum of all requests. Promise.all starts every request at once, so the total time is about the time of the slowest request.