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.

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

its not a mongodb connection rows. Actually its just an array.. see my editd post..
Could you create a fiddle for this then?
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
      }

     });  

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.