The JavaScript Array.fromAsync() method is a powerful tool that creates an array from an array-like or iterable object, where each element is produced by an asynchronous function. This method allows for asynchronous processing within the array creation, making it particularly useful for operations like fetching data or performing asynchronous computations.
Syntax
Array.fromAsync(arrayLike, [mapFn], [thisArg])
Parameters
Parameters | Descriptions |
---|---|
arrayLike | Required. An array-like or iterable object to convert to an array. |
mapFn | Optional. An asynchronous mapping function to call on every element of the array. |
thisArg | Optional. Value to use as this when executing mapFn. |
Return Value
Return Value | Description |
---|---|
Promise | Returns a promise that resolves to a new array instance from the provided array-like or iterable object. If mapFn is provided, it is called on each element before adding it to the new array. |
Example 1: Converting a String to an Array with a Delay
This code converts a string to an array, with a delay applied to each element transformation.
async function delayChar(char) { return new Promise(resolve => setTimeout(() => resolve(char), 100)); } Array.fromAsync("hello", delayChar).then(arr => console.log(arr));
Output
["h", "e", "l", "l", "o"]
Example 2: Fetching Data Asynchronously
This code creates an array from a list of URLs by fetching data from each URL asynchronously.
async function fetchData(url) { let response = await fetch(url); return await response.json(); } let urls = ["https://api.example.com/data1", "https://api.example.com/data2"]; Array.fromAsync(urls, fetchData).then(arr => console.log(arr));
Output:
[/* data from data1 */, /* data from data2 */]
Example 3: Converting a Set to an Array Asynchronously
This code converts a set of numbers to an array with an asynchronous function applied to each number.
async function multiplyByTwo(num) { return num * 2; } let set = new Set([1, 2, 3]); Array.fromAsync(set, multiplyByTwo).then(arr => console.log(arr));
Output:
[2, 4, 6]
Example 4: Using Array.fromAsync() with an Async Arrow Function
This code demonstrates using Array.fromAsync() with an async arrow function to transform each element.
let arr = [1, 2, 3, 4]; Array.fromAsync(arr, async num => num * 3).then(result => console.log(result));
Output:
[3, 6, 9, 12]
Example 5: Handling Errors in Array.fromAsync() Method
This code shows how to handle errors during the asynchronous array creation process.
async function throwErrorIfOdd(num) { if (num % 2 !== 0) { throw new Error(`Odd number: ${num}`); } return num; } let nums = [1, 2, 3, 4]; Array.fromAsync(nums, throwErrorIfOdd) .then(arr => console.log(arr)) .catch(error => console.error(error));
Output:
Error: Odd number: 1
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
121 | 121 | 115 | 107 | 16.4 |