I'm using a for each to process a list and i want that element n to be executed only when element n-1 is over:
var elements = ["stuff1", "stuff2", "stuff3"];
elements.forEach(function(element){
someAsyncFunction(element, function(){
console.log('do more stuff');
});
});
I need that they wait for each other and execute in the right order.
EDIT : I bumped into process.nextTick(), but I'm not sure if it guarantees the waiting and order.
Just store the elements in an array exactly the same way as you did in your question. Then use elements.shift() to retrieve and remove the first element.
var elements = ["stuff1", "stuff2", "stuff3"];
(function next () {
if (!elements.length) {
return;
}
var element = elements.shift();
someAsyncFunction(element, function (err, result) {
…
next();
});
})();
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