Array.fromAsync builds an array from an async or sync iterable and returns a promise that resolves once every value has been awaited and collected in order. It is the async cousin of Array.from: where Array.from reads a sync source and hands back an array, Array.fromAsync can also drain an async iterable, awaits each value, and hands back a Promise. Implement it yourself as arrayFromAsync — see the MDN reference for the full spec.
arrayFromAsync(input, mapFn?): Promise<Array>
// input : an async iterable (has [Symbol.asyncIterator]),
// a sync iterable (has [Symbol.iterator]),
// or an array-like { length, 0, 1, ... } whose elements may be promises
// mapFn : optional (value, index) => mapped — runs on each awaited value;
// if it returns a promise, that is awaited too
// A sync iterable of promises resolves to their resolved values.
await arrayFromAsync([Promise.resolve(1), Promise.resolve(2), 3]); // [1, 2, 3]
// An async generator, drained in order, with a mapFn applied to each value.
async function* nums() {
yield 1;
yield 2;
yield 3;
}
await arrayFromAsync(nums(), (n, i) => n * 10 + i); // [10, 21, 32]
Promise<Array>, never a bare array.[Symbol.asyncIterator]) is drained with for await; a sync iterable (has [Symbol.iterator]) or an array-like is iterated and each element is awaited.k is collected before value k + 1 is requested. This is not Promise.all, and the difference matters for a lazy async generator.mapFn(value, index) — receives the awaited value and its 0-based index. If mapFn returns a promise, that promise is awaited before the result is collected.mapFn call rejects, the returned promise rejects and iteration stops.Array.fromAsync — write the iteration yourself with an async function and for await.