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?

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

1 Answer 1

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!');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.