I am working on the code snippet below. I have an array of JSON objects called ‘stuObjList’. I want to loop through the array to find specific JSON objects with a certain flag set, and then make a database call to retrieve more data.
Of course, the FOR loop doesn’t wait for the database call to return and reaches the end of with j == length. And when the database call returns, the index ‘j’ is beyond the array index. I understand how node.js works and this is the expected behavior.
What is the workaround here? How can I achieve what I am trying to achieve?
...............
...............
...............
else
{
console.log("stuObjList.length: " + stuObjList.length);
var j = 0;
for(j = 0; j < stuObjList.length; j++)
{
if(stuObjList[j]['honor_student'] != null)
{
db.collection("students").findOne({'_id' : stuObjList[j]['_id'];}, function(err, origStuObj)
{
var marker = stuObjList[j]['_id'];
var major = stuObjList[j]['major'];
});
}
if(j == stuObjList.length)
{
process.nextTick(function()
{
callback(stuObjList);
});
}
}
}
});
“async” is an very popular module for abstracting away asynchronous looping and making your code easier to read/maintain. For example:
So you could use it like this:
Note that .forEach() will call your iterator function for each element in stuObjList “in parallel” (i.e., it won’t wait for one iterator function to finish being called for one array element before calling it on the next array element). This means that you can’t really predict the order in which the iterator functions–or more importantly, the database calls–will run. End result: unpredictable order of honor students. If the order matters, use the .forEachSeries() function.