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?

koikoi
  • 107
  • 1
  • 6
  • 1
    Read the documentation. You want `async.series`, and you need to actually call the callback. – SLaks Aug 10 '15 at 22:12
  • Sorry I forgot to add the callback, I was just typing up a quick example. But thank you! :) – koikoi Aug 11 '15 at 15:20

1 Answers1

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!');
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180