JavaScript Array.fromAsync() Method

Array 对象参考手册JavaScript Array Object


Example

Create an array from an async iterable:

const asyncIterable = (async function* () { for (let i = 0; i < 5; i++) { await new Promise((resolve) => setTimeout(resolve, 10 * i)); yield i; } })(); Array.fromAsync(asyncIterable).then((array) => console.log(array)); // [0, 1, 2, 3, 4]

Try it Yourself »

Definition and Usage

Array.fromAsync() is a relatively new static method in JavaScript that allows you to create a new array from an async iterable, an iterable, or an array-like object. This method returns a Promise that resolves to a new array instance.

In simple terms, it is the asynchronous version of Array.from(), specifically designed for handling asynchronous data sources.


Basic Syntax

Array.fromAsync(asyncIterable)
Array.fromAsync(iterable)
Array.fromAsync(arrayLike)
Array.fromAsync(asyncIterable, mapFn)
Array.fromAsync(asyncIterable, mapFn, thisArg)

Parameter Description

  • asyncIterable: An async iterable (such as an async generator)
  • iterable: An iterable (such as an array, string, Set, etc.)
  • arrayLike: An array-like object (an object with a length property and indexed elements)
  • mapFn(Optional): A mapping function that is called on each element
  • thisArg(Optional): The value to use as this when executing mapFn

Return Value

Returns a Promise that resolves to a new array.


Browser Support

Array.fromAsync() is a relatively new feature that, as of 2023, is only supported in newer versions of browsers:

  • Chrome 117+
  • Firefox 115+
  • Safari 16.4+
  • Node.js 21+

For unsupported environments, you can use a polyfill or implement similar functionality yourself.

The numbers in the table indicate the first browser version that supports the method.

Method
fromAsync() 117+ 121+ 115+ 16.4+ 81.0+

Usage Examples

Example 1: Create an Array from an Async Generator

Example

async function* asyncGenerator() {
  yield 1;
  yield 2;
  yield 3;
}

(async () => {
  const result = await Array.fromAsync(asyncGenerator());
  console.log(result); // Output: [1, 2, 3]
})();

Example 2: Create an Array from a Regular Iterable

Example

const set = new Set([1, 2, 3]);

(async () => {
  const result = await Array.fromAsync(set);
  console.log(result); // Output: [1, 2, 3]
})();

Example 3: Using a Mapping Function

Example

async function* asyncNumbers() {
  yield 1;
  yield 2;
  yield 3;
}

(async () => {
  const result = await Array.fromAsync(asyncNumbers(), x => x * 2);
  console.log(result); // Output: [2, 4, 6]
})();

Differences from Array.from()

Although Array.fromAsync() and Array.from() look similar, they have several key differences:

1. Handling Asynchronous Data Sources

Array.fromAsync() can handle async iterables, while Array.from() cannot.

2. Return Value

Array.from() returns an array directly, while Array.fromAsync() returns a Promise.

3. Execution Timing

Array.from() is executed synchronously, while Array.fromAsync() is executed asynchronously.


Practical Application Scenarios

Scenario 1: Handling Paginated API Data

Example

async function* paginatedFetcher() {
  let page = 1;
  while (true) {
    const response = await fetch(`https://api.example.com/data?page=${page}`);
    const data = await response.json();
    if (data.length === 0) break;
    yield* data;
    page++;
  }
}

(async () => {
  const allData = await Array.fromAsync(paginatedFetcher());
  console.log(allData); // Merge data from all pages into one array
})();

Scenario 2: Handling Results of Multiple Asynchronous Operations

Example

const promises = [
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.resolve(3)
];

(async () => {
  const results = await Array.fromAsync(promises);
  console.log(results); // Output: [1, 2, 3]
})();

Summary

Array.fromAsync() is a powerful tool, especially suitable for handling asynchronous data collections. It simplifies the process of creating arrays from asynchronous data sources, making code cleaner and easier to maintain. Although browser support is not yet widespread, over time it will become one of the standard methods for handling asynchronous data collections.

Remember, when you need to create an array from an asynchronous data source, Array.fromAsync() is your good helper!

Array 对象参考手册JavaScript Array Object

Other Extensions