JavaScript - fromAsync() method

revision:


Category : array

The Array.fromAsync() static method creates a new, shallow-copied Array instance from an async iterable, iterable, or array-like object.

Syntax :

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

Parameters:

arrayLike : an async iterable, iterable, or array-like object to convert to an array.

mapFn : optional. A function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and "mapFn"'s return value is added to the array instead (after being awaited). The function is called with the following arguments:

element : the current element being processed in the array. Because all elements are first awaited, this value will never be a thenable.
index : the index of the current element being processed in the array.

thisArg : optional. Value to use as "this" when executing "mapFn".

Examples:

            Array.fromAsync(
                new Set([Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)]),
            ).then((array) => console.log(array));
            // [1, 2, 3]
              
            function delayedValue(v) {
                return new Promise((resolve) => setTimeout(() => resolve(v), 100));
            }
            Array.fromAsync(
               [delayedValue(1), delayedValue(2), delayedValue(3)],
               (element) => delayedValue(element * 2),
            ).then((array) => console.log(array));
            // [2, 4, 6]
        

Practical examples

example:

code:
                    
                

example:
code:
                    
                

example:
code: