1

I have to implement a program in node.js which looks like the following code snippet. It has an array though which I have to traverse and match the values with database table entries. I need to wait till the loop ends and send the result back to the calling function:

var arr=[];
arr=[one,two,three,four,five];

for(int j=0;j<arr.length;j++) {

   var str="/^"+arr[j]+"/";

   // consider collection  to be a variable to point to a database table

   collection.find({value:str}).toArray(function getResult(err, result) {
     //do something incase a mathc is found in the database...
   });

}

However, as the str="/^"+arr[j]+"/"; (which is actually a regex to be passed to find function of MongoDB in order to find partial match) executes asynchronously before the find function, I am unable to traverse through the array and get required output.

Also, I am having hard time traversing through array and send the result back to calling function as I do not have any idea when will the loop finish executing.

1 Answer 1

4

Try using async each. This will let you iterate over an array and execute asynchronous functions. Async is a great library that has solutions and helpers for many common asynchronous patterns and problems.

https://github.com/caolan/async#each

Something like this:

var arr=[];
arr=[one,two,three,four,five];

asych.each(arr, function (item, callback) {
  var str="/^"+item+"/";
  // consider collection  to be a variable to point to a database table
  collection.find({value:str}).toArray(function getResult(err, result) {
    if (err) { return callback(err); }
    // do something incase a mathc is found in the database...
    // whatever logic you want to do on result should go here, then execute callback
    // to indicate that this iteration is complete
    callback(null);
  });
} function (error) {
  // At this point, the each loop is done and you can continue processing here
  // Be sure to check for errors!
})
Sign up to request clarification or add additional context in comments.

1 Comment

@user3256628 if this answer helped you, please consider marking this as the answer to this question.

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.