Array.fromAsyncLoading saved progress…

Array.fromAsync

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.

Signature

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

Examples

// 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]

Notes

  • Always returns a promise — even a sync iterable of plain values gives you Promise<Array>, never a bare array.
  • Two input protocols — an async iterable (has [Symbol.asyncIterator]) is drained with for await; a sync iterable (has [Symbol.iterator]) or an array-like is iterated and each element is awaited.
  • In order, one at a time — values are awaited sequentially: value k is collected before value k + 1 is requested. This is not Promise.all, and the difference matters for a lazy async generator.
  • Optional 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.
  • Rejections propagate — if any awaited value or mapFn call rejects, the returned promise rejects and iteration stops.
  • Don't call the real Array.fromAsync — write the iteration yourself with an async function and for await.
Loading editor…