简体   繁体   中英

node.js async for loop

My Scenario:

Inside a forEach loop i executed a function with callback as like below:

var rows = [];
rows.forEach(function(elem, i){
///done some stuff

     client.search(query).then(function(facResult){
     //done some stuff         
     });    
});

My problem is for first iteration the "client.search(query)" is executed before finishing this stuff the second iteration is started because client.search(query) is executed with callback. I have to push first all result into an array.

So before i am getting first result the second is appended, sometimes i am not getting even the first result.

What i have to do to execute the for loop in order. I searched a lot , some suggestions is to use timedelay , but i don't need that. Help me to solve this. Thanks in advance.

You are running into race-condition issues because of using 'forEach'. Instead of getting all the rows into 'rows', use a 'cursor' instead.

You can see the following answer for implementation which is similar to your use-case : https://stackoverflow.com/a/18119789/802651

I used async library for this as like below:

async.forEach(myVar.rows, function (elem, next){ 

    client.search(query).then(function(facResult){
     //done some stuff      
      if(--myVar.rows.length == 0){
          loop finishes //done some stuff
      }

     });  

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM