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?
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!');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With