How to execute javascript foreach in series?
GregLimo
Posted on November 25, 2021
Hey buddies, On a piece of code I am working on there is a number of async functions that operate on an array of data. The way I would expect to handle this is using the standard forEach function. The problem found is that even if you await in the callback in the for loop this does not help:
const takesLongToRun = async additionalText => {
setTimeout (() => {
console.log (`Long function done :) ${additionalText}`);
}, 3000);
};
const mainFunc = async () => {
const numbers = [1, 2, 3, 4];
numbers.forEach (async num => {
console.log (num);
await takesLongToRun (num);
});
};
mainFunc ();
which outputs:
1
2
3
4
Long function done :) 1
Long function done :) 2
Long function done :) 3
Long function done :) 4
So the functions do run in order but it doesn't wait for each value to complete before proceeding to next, what I expect is:
1
Long function done :) 1
2
Long function done :) 2
3
Long function done :) 3
4
Long function done :) 4
After doing a bit of googling I found that this is an issue with forEach and instead the for of syntax seem to solve it in theory. I changed the code as below but still worked the same.
const mainFunc = async () => {
const numbers = [1, 2, 3, 4];
for (const num of numbers) {
console.log (num);
await takesLongToRun (num);
}
};
mainFunc()
The result is still the same, I will really appreciate any insight on this from anyone who has experienced it before. Thanks.
Posted on November 25, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.