Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For iteration with async functions

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.

like image 263
dege Avatar asked Dec 17 '25 18:12

dege


1 Answers

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();
    });
})();
like image 84
kay Avatar answered Dec 19 '25 06:12

kay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!