Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause/Timeout in async.forEach NodeJS

So lets say fruits is an array containing 4 items What I expected was that the code below would print fruit with a 4 second delay between each fruit.

var fruits = ['blueberries', 'strawberries', 'mango', 'peaches'];
async.forEach(fruits, functions(fruit, next) { 
     setTimeout(function() {
          console.log(fruit);
     }, 4000);
})

The actual behaviour is that it waits 4 seconds, and then prints the entire list. :\ Does anybody know how to achieve my expected behaviour?

like image 953
koikoi Avatar asked Jan 07 '23 19:01

koikoi


1 Answers

async.forEach runs through the array in parallel, meaning it will run the function for each item in the array immediately, and then when all of them execute the callback, the callback function (that you failed to include) will be called.

In your case, you want to run through the array one at a time, or, in a series, so you'll need the .eachSeries method.

var fruits = ['blueberries', 'strawberries', 'mango', 'peaches'];
async.eachSeries(fruits, function (fruit, next) { 
     setTimeout(function() {
          console.log(fruit);
          next(); // don't forget to execute the callback!
     }, 4000);
}, function () {
     console.log('Done going through fruits!');
});
like image 118
Kevin B Avatar answered Jan 16 '23 00:01

Kevin B