Array.fromAsync()
The Array.fromAsync()
static method in JavaScript creates a new array from an array-like or iterable object, resolving any asynchronous operations during the process. It can also apply a mapping function to each item before resolving it.
Syntax
Array.fromAsync(arrayLike)
Array.fromAsync(arrayLike, mapFn)
Array.fromAsync(arrayLike, mapFn, thisArg)
Parameters
Parameter | Description |
---|---|
arrayLike | An array-like or iterable object to convert into an array. It can include asynchronous values like Promises. |
mapFn (optional) | A mapping function to apply to each item before including it in the new array. It can also return a Promise. |
thisArg (optional) | A value to use as this when executing the mapFn . |
Return Value
The Array.fromAsync()
method returns a Promise that resolves to a new array after processing all asynchronous values and applying the mapping function (if provided).
Examples
1. Converting an Array-Like Object
This example demonstrates converting an array-like object to a proper array, resolving Promises in the process.
const arrayLike = {
0: Promise.resolve(10),
1: 20,
2: Promise.resolve(30),
length: 3,
};
Array.fromAsync(arrayLike).then(console.log);
Output
[10, 20, 30]
- The
Array.fromAsync()
method processes each property of the array-like object, resolving Promises and including resolved values in the new array.
2. Using a Mapping Function
In this example, a mapping function is used to double each resolved value.
const promises = [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)];
Array.fromAsync(promises, async (value) => value * 2).then(console.log);
Output
[2, 4, 6]
- The
mapFn
multiplies each resolved value by 2 before including it in the new array.
3. Using thisArg
with a Mapping Function
The thisArg
parameter lets you specify the this
value for the mapping function.
const arrayLike = [1, 2, 3];
const multiplier = {
factor: 3,
multiply(value) {
return value * this.factor;
},
};
Array.fromAsync(arrayLike, multiplier.multiply, multiplier).then(console.log);
Output
[3, 6, 9]
- The mapping function multiplies each element by
this.factor
, which is provided by themultiplier
object.
4. Handling Asynchronous Mappings
This example demonstrates handling asynchronous operations within the mapping function.
const urls = [
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/posts/2',
'https://jsonplaceholder.typicode.com/posts/3',
];
Array.fromAsync(urls, async (url) => {
const response = await fetch(url);
const data = await response.json();
return data.title;
}).then(console.log);
Output
[
"Title of Post 1",
"Title of Post 2",
"Title of Post 3"
]
- The
mapFn
fetches data from the URLs and extracts thetitle
property from the response.