Pause/Timeout in async.forEach NodeJS
Asked Answered
N

1

5

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?

Nachison answered 10/8, 2015 at 22:9 Comment(2)
Read the documentation. You want async.series, and you need to actually call the callback.Indwell
Sorry I forgot to add the callback, I was just typing up a quick example. But thank you! :)Nachison
R
10

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!');
});
Recur answered 10/8, 2015 at 22:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.