Materialize asynchronous streams
Collect values produced over time by an async generator or another async iterable.
JavaScript · Function
Array.fromAsync() builds a new array from an async iterable, iterable, or array-like object. It returns a promise and awaits source values and optional mapping results.
Array.fromAsync() consumes an async iterable, ordinary iterable, or array-like value and returns a promise for a new array. It awaits values from non-async sources and also awaits the result of an optional mapping function.
Array.fromAsync(items)
Array.fromAsync(items, mapFn)
Array.fromAsync(items, mapFn, thisArg)| Name | Type | Description |
|---|---|---|
items | async iterable, iterable, or array-like object | An async iterable, iterable, or array-like object to convert to an array. |
mapFn | function | Optional function called for every element; its returned value is awaited and added to the result. |
thisArg | any | Optional value used as this when executing mapFn. |
A Promise fulfilled with a new Array instance.
const delayed = (value, ms) => new Promise(resolve => setTimeout(() => resolve(value), ms));
const result = await Array.fromAsync(
[1, 2, 3],
async value => delayed(value * 2, 10),
);
console.log(result); // [2, 4, 6]The mapping function runs for each input and its result is awaited before the resulting array is fulfilled.
Collect values produced over time by an async generator or another async iterable.
Convert Set, Map, or indexed array-like data while resolving promise-valued elements.
Apply asynchronous transformation logic while collecting results into an array.
It returns a promise whose fulfillment value is a new Array instance. The source may be async iterable, iterable, or array-like.
Follow-up: How does it differ from Array.from()? Array.fromAsync() supports async iterables and awaits values, whereas Array.from() returns the array synchronously.
The first argument can be an async iterable, an ordinary iterable, or an array-like object. This lets it collect values from sources such as async generators, Set, Map, or indexed objects.
Follow-up: What happens when a source is both async and synchronous iterable? The async-iterable handling takes precedence.
mapFn is called for each element, and its return value is awaited before it is placed in the resulting array. thisArg optionally supplies the this value used while calling mapFn.
Follow-up: Are synchronous-source values passed to mapFn as unresolved promises? No; those values are awaited first, so mapFn receives the resolved elements.
Array.from()Array.prototype.map()for await...ofAsyncIterator