What is the best way to ensure that the for loop completes its processing before updating the MongoDB database in this code snippet:
var userIdArray = [] // contains 100000 userIds
User.find({'_id': {$in: userIdArray}}, 'name', function(err, result){
var thisTime = new Date().getTime();
var usersArray = [];
for (var i = 0; i < result.length; i++) {
var user = result[i];
var userObject = {
userId: user['_id'],
userName: user.name,
time: thisTime
}
usersArray.push(userObject);
};
Model.update(id,
{$pullAll: {userIds: userIdArray}, $push: {users: {$each: usersArray}}},
function(err, result) {
//continue to do stuff
}
);
});
Model.update) is executed after the for loop, always. Because there is nothing async inside yourforloop. See: stackoverflow.com/questions/16336367/…Model.updatewill be executed after the synchronous operations in the loop, but not always after the async tasks you add inside. Node.js will "check" for completed async tasks once your synchronous code is executed (that is, once theModel.updatetask is queued) and will execute it's callbacks. You can read more about the Event Loop in Node.js here: blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop