Sub topic 13
Collecting Async Results with Array.fromAsync
Sometimes you don't want to process an async sequence item by item. You want all of it in an array so you can sort it, count it, or pass it to code that expects an array. Array.fromAsync does this in one call. It is the async counterpart of Array.from.
This chapter assumes you already know for await...of, async generators, early exit with return(), and the difference between sequential and concurrent awaiting, all covered in earlier chapters. You also need a runtime that supports Array.fromAsync: Node.js 22 or later, Chrome 121+, Firefox 115+, or Safari 16.4+. The examples use top-level await, so save them as .mjs files or run them in a browser console.
The Basic Shape
Array.fromAsync(items, mapFn, thisArg) returns a Promise. That Promise resolves to a new array holding every value from items, in order.
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;
}
}
const values = await Array.fromAsync(countdown(3));
console.log(values); // [ 3, 2, 1 ] after about 300 msThis one line replaces the loop you would otherwise write by hand:
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;
}
}
const values = [];
for await (const n of countdown(3)) {
values.push(n);
}
console.log(values); // [ 3, 2, 1 ]The two versions behave almost identically. Array.fromAsync pulls one value, waits for it, stores it, and then pulls the next. It never asks for a second value while the first is still pending.
What It Accepts
Array.fromAsync takes three kinds of input. It checks for them in this order:
- An async iterable: an object with a
Symbol.asyncIteratormethod. Values come fromawait iterator.next(). - A sync iterable: an object with a
Symbol.iteratormethod, such as an array,Set, orMap. Each value is awaited, so an array of promises becomes an array of their results. - An array-like: an object with a
lengthproperty and numeric keys. Each element is read by index and awaited.
If the input is none of these, for example null or undefined, the returned Promise rejects with a TypeError. It does not throw synchronously.
Here is the array-like case, which is easy to forget:
const arrayLike = {
length: 3,
0: Promise.resolve('a'),
1: 'b',
2: new Promise((resolve) => setTimeout(() => resolve('c'), 50))
};
console.log(await Array.fromAsync(arrayLike)); // [ 'a', 'b', 'c' ]One detail matters for async iterables. A value that an async iterator yields is not awaited a second time. Async generators already await anything you yield, so this rarely shows up in practice. A hand-written async iterator that returns { value: somePromise, done: false } will put the Promise object itself into the array. A sync iterable's values are always awaited.
The Mapping Function
The optional second argument, mapFn, is called as mapFn(value, index) for every element. Its return value is awaited before it goes into the array, so mapFn can be an async function.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* ids() {
yield 101;
yield 102;
yield 103;
}
async function lookupUser(id) {
await sleep(50); // stand-in for a network call
return { id, name: `user-${id}` };
}
const users = await Array.fromAsync(ids(), (id, index) => {
console.log(`looking up #${index}`);
return lookupUser(id);
});
console.log(users.map((u) => u.name)); // [ 'user-101', 'user-102', 'user-103' ]The third argument, thisArg, sets this inside mapFn. It only matters if mapFn is a regular function. Arrow functions ignore it.
Mapping inside Array.fromAsync differs from calling .map() on the result afterwards. With .map() afterwards, an async callback leaves you with an array of Promises. With mapFn, each result is awaited, so you get the resolved values.
It Is Sequential, Including mapFn
Array.fromAsync is sequential. It calls mapFn for element n + 1 only after the Promise for element n has settled. If mapFn starts the slow work, the calls run one after another.
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
const delays = [300, 200, 100];
console.time('fromAsync with mapFn');
await Array.fromAsync(delays, (ms) => sleep(ms, ms));
console.timeEnd('fromAsync with mapFn'); // about 600 ms
console.time('Promise.all');
await Promise.all(delays.map((ms) => sleep(ms, ms)));
console.timeEnd('Promise.all'); // about 300 ms
console.time('fromAsync over started promises');
await Array.fromAsync(delays.map((ms) => sleep(ms, ms)));
console.timeEnd('fromAsync over started promises'); // about 300 msIn the third case, delays.map(...) starts all three timers before Array.fromAsync sees them. Array.fromAsync then awaits Promises that are already running, so the total time is set by the slowest one. Where the work starts decides the timing, not which collection function you call.
Choosing the Right Collector
| Situation | Best tool | Why |
|---|---|---|
| Async generator, stream, or paginated source | `Array.fromAsync(source)` | Pulls values in order and respects backpressure |
| Async source plus a per-item async transform that must run in order | `Array.fromAsync(source, mapFn)` | Each transform finishes before the next one starts |
| Array of independent tasks that should run together | `Promise.all(tasks)` | Runs them at once and handles every rejection |
| Need every outcome, including failures | `Promise.allSettled(tasks)` | Never rejects, returns a status for each item |
| Need to stop early, process as you go, or the source is huge | `for await...of` | No full array held in memory, and you can `break` |
Errors and Cleanup
The returned Promise rejects when any of these happens:
- The source throws, or one of its
next()Promises rejects. - A sync or array-like element is a rejected Promise.
mapFnthrows or returns a rejected Promise.
When mapFn fails and the source is an iterator, Array.fromAsync closes the iterator by calling its return() method before it rejects. This is the same cleanup that break or an exception triggers inside for await...of, so a generator's finally block still runs.
async function* source() {
console.log('source opened');
try {
yield 1;
yield 2;
yield 3;
} finally {
console.log('source closed');
}
}
try {
await Array.fromAsync(source(), (n) => {
if (n === 2) throw new Error(`bad item ${n}`);
return n * 10;
});
} catch (err) {
console.log('Caught:', err.message);
}
// source opened
// source closed
// Caught: bad item 2Two more points about failures:
- Partial results are discarded. You get an error or a complete array, never the items collected before the error. If you need partial results, use a
for await...ofloop and push into an array you declared outside thetry. - A failing source is not closed for you. If the source itself throws, it has already finished, so there is no
return()call. Any cleanup belongs in the source's ownfinally.
Infinite and Very Large Sources
Array.fromAsync only resolves after the source reports done: true. An endless source, such as a ticker, a websocket feed, or a generator with while (true), will never resolve, and the internal array keeps growing until memory runs out.
Bound the source first with a limiting generator like the take() helper from the pipelines chapter:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* forever() {
let i = 0;
while (true) {
await sleep(10);
yield i++;
}
}
async function* take(source, limit) {
if (limit <= 0) return;
let count = 0;
for await (const item of source) {
yield item;
if (++count >= limit) return;
}
}
console.log(await Array.fromAsync(take(forever(), 5))); // [ 0, 1, 2, 3, 4 ]When take() returns, its for await...of loop exits and calls return() on forever(), so the upstream generator stops too.
For finite but large sources, such as a multi-gigabyte log read with readline, collecting into an array defeats the purpose of streaming. Count, filter, or aggregate inside a for await...of loop instead. Call Array.fromAsync only once the output is small.
Subclasses and the Constructor
Like Array.from, Array.fromAsync uses this as the constructor, so calling it on an Array subclass produces an instance of that subclass:
class Batch extends Array {
total() {
return this.reduce((sum, n) => sum + n, 0);
}
}
async function* nums() {
yield 1;
yield 2;
yield 3;
}
const batch = await Batch.fromAsync(nums());
console.log(batch instanceof Batch, batch.total()); // true 6Because of this, the method must be called on its constructor. Pulling it off as const f = Array.fromAsync and calling f(source) with no this still works, because it falls back to a plain array, but Batch.fromAsync loses its subclass that way.
A Fallback for Older Runtimes
If you must support runtimes without Array.fromAsync, a small helper covers the common cases. It reuses for await...of, which already awaits sync values and closes the iterator when mapFn throws.
async function fromAsync(items, mapFn) {
if (items == null) throw new TypeError('items is null or undefined');
const out = [];
let index = 0;
const iterable =
typeof items[Symbol.asyncIterator] === 'function' ||
typeof items[Symbol.iterator] === 'function';
if (iterable) {
for await (const value of items) {
out.push(mapFn ? await mapFn(value, index) : value);
index++;
}
} else {
for (let i = 0; i < items.length; i++) {
const value = await items[i];
out.push(mapFn ? await mapFn(value, i) : value);
}
}
return out;
}
async function* letters() {
yield 'x';
yield 'y';
}
console.log(await fromAsync(letters(), (s, i) => s + i)); // [ 'x0', 'y1' ]This helper skips subclass support and thisArg. For full compliance, use the polyfill from core-js (core-js/actual/array/from-async).
Exercise
An array urls holds 20 URLs. A teammate writes await Array.fromAsync(urls, (u) => fetch(u).then((r) => r.json())) and complains that it is slow. Explain why, and rewrite it so all requests run at the same time.
Show answer
Array.fromAsync calls mapFn for the next element only after the previous mapped Promise has settled, so the 20 fetches run one after another. Start them all first and use Promise.all: await Promise.all(urls.map((u) => fetch(u).then((r) => r.json()))). Don't swap in Array.fromAsync(urls.map(...)) either. It would also run concurrently, but a rejection while an earlier fetch is pending could be reported as unhandled.
Exercise
An async generator yields 1, 2, 3 inside try/finally, and the finally block logs 'closed'. What does await Array.fromAsync(gen(), async (n) => { if (n === 2) throw new Error('x'); return n; }) log, and what does the expression produce?
Show answer
It logs 'closed', because Array.fromAsync calls the generator's return() when mapFn rejects. The expression then rejects with Error('x'). No partial array [1] is returned; the result already collected for item 1 is discarded.
Exercise
A hand-written async iterator's next() resolves to { value: Promise.resolve(5), done: false } once and then { done: true }. What does Array.fromAsync return for it, and how does that differ from Array.fromAsync([Promise.resolve(5)])?
Show answer
For the async iterable, the yielded value is not awaited again, so the result is an array holding the Promise object itself: [Promise]. For the sync array, each element is awaited, so the result is [5].