EN
JavaScript - async Array map() method
8 points
In this short article, we would like to show how to use Array
map()
asynchronously in JavaScript.
Quick solution:
xxxxxxxxxx
1
const array = [ /* ... */ ];
2
3
const result = await Promise.all(array.map(async (item) => { /* return ... */ });
In this section, you can find reusable arrow function.
xxxxxxxxxx
1
const mapAsync = async (array, callback) => await Promise.all(array.map(callback));
2
3
4
// Usage example:
5
6
;(async () => {
7
const array = [1, 2, 3];
8
const result = await mapAsync(array, async (item) => `item-${item}`);
9
console.log(result);
10
})();
In this section, Array
class was extended by additional mapAsync()
method.
xxxxxxxxxx
1
Array.prototype.mapAsync = async function(callback) {
2
return await Promise.all(this.map(callback));
3
};
4
5
6
// Usage example:
7
8
;(async () => {
9
const array = [1, 2, 3];
10
const result = await array.mapAsync(async (item) => `item-${item}`);
11
console.log(result);
12
})();
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.
xxxxxxxxxx
1
const mapAsync = async (array, callback) => {
2
const result = [];
3
for (let i = 0; i < array.length; ++i) {
4
result.push(await callback(array[i]));
5
}
6
return result;
7
};
8
9
10
// Usage example:
11
12
;(async () => {
13
const array = [1, 2, 3];
14
const result = await mapAsync(array, async (item) => `item-${item}`);
15
console.log(result);
16
})();