Reputation: 105
So i have a piece of code like here and need to refactor it to use map/forEach.
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
But when i use map like below it just parses the whole json without waiting for individual entries of the array to send each entry with delay in callback function.
async function asyncForEach(array, callback) {
await array.map(async (item, index) => {
await callback(array[index], index, array);
});
}
Any help would be appreciated.
Upvotes: 0
Views: 704
Reputation: 138427
You have to use Promise.all
as await
on an array (although it contains promises) does nothing:
await Promise.all(array.map(/*...*/));
I'd write it as:
const asyncForEach = (array, callback) =>
Promise.all(array.map(callback));
Upvotes: 2