0

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.

Subburaj
  • 4,631
  • 6
  • 32
  • 75
  • You can use async library. Look at this post: http://stackoverflow.com/questions/9644197/sequential-execution-in-node-js – Aviv Shaked Feb 11 '15 at 05:44

2 Answers2

0

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

Community
  • 1
  • 1
Adarsh Konchady
  • 2,240
  • 4
  • 23
  • 42
0

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
      }

     });  

});
Subburaj
  • 4,631
  • 6
  • 32
  • 75