08-02-2023, 04:34 PM
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);
});
}
}
}
});
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);
});
}
}
}
});