Languages
[Edit]
EN

JavaScript - async Array map() method

8 points
Created by:
maryam
1181

In this short article, we would like to show how to use Array map() asynchronously in JavaScript.

Quick solution:

const array = [ /* ... */ ];

const result = await Promise.all(array.map(async (item) => { /* return ... */ });

 

Reusable example

Solution 1

In this section, you can find reusable arrow function.

// ONLINE-RUNNER:browser;

const mapAsync = async (array, callback) => await Promise.all(array.map(callback));


// Usage example:

;(async () => {
    const array = [1, 2, 3];
    const result = await mapAsync(array, async (item) => `item-${item}`);
    console.log(result);
})();

Solution 2

In this section, Array class was extended by additional mapAsync() method.

// ONLINE-RUNNER:browser;

Array.prototype.mapAsync = async function(callback) {
    return await Promise.all(this.map(callback));
};


// Usage example:

;(async () => {
    const array = [1, 2, 3];
    const result = await array.mapAsync(async (item) => `item-${item}`);
    console.log(result);
})();

 

Improved solution

In this section, you can find function that do not generate promises array. It can be useful when we want to work on big arrays in environment where RAM is limited. Each callback function call is performed one after one.

// ONLINE-RUNNER:browser;

const mapAsync = async (array, callback) => {
    const result = [];
    for (let i = 0; i < array.length; ++i) {
        result.push(await callback(array[i]));
    }
    return result;
};


// Usage example:

;(async () => {
    const array = [1, 2, 3];
    const result = await mapAsync(array, async (item) => `item-${item}`);
    console.log(result);
})();

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join