I have a case in which I am running a loop for n times, and for each loop call, I am to check the presence of a value in a couple of mongo collections say A, and B , and then upsert in a collection C
for (i=0;i<n;i++)
{
Console.log("started call to doSomething for " + i);
doSomething(i);
Console.log("End call to doSomething for " + i);
}
function doSomething(i)
{
console.log("started doing something for " + i);
calltoMongo(i);
}
function calltoMongo(i);
{
common.db.collection.find(err,result)
{
console.log("here for " + i);
common.db.collection.insert(<some object >);
}
}
Above is just pseudo code of what I have, the output comes very crazy lets say i run it for 3 elements in my for loop
the output would be
started call to doSomething for 1
started doing something for 1
End call to doSomething for 1
started call to doSomething for 2
started doing something for 2
End call to doSomething for 2
here for 2
here for 2
I am at my wits end, I understand something funny happening due to scope resolution and that because only last element value remains when the loop ends, and the mongo side code starts working only after wards the value that remains in scope is the last value, But i don't know a way to fix it for real, even if I put sleep at end of call to Mongo function , it doesn't help.