问题
I've been on this for hours and can't seem to find the answer. The problem is that I have a call to a mongoDB inside a for loop. I'm using a latch so the for waits for the call to end before advancing again. Here's my code:
var latch = true;
for (var i=0; i<array.length; i++) {
while(latch == false){}
Table1.find({}, function(err, result){
... some code ...
latch = true;
});
latch = false;
}
The problem is that it doesn't even run the callback from Table1.find(), it just gets blocked on the while. Can anyone help me with this?
回答1:
The for loop will never proceed past the while loop (as you've created an infinite loop).
There are several ways to handle async code within loops in node, including counter variables outside the function, and tail-recursion. You can see some examples here: http://metaduck.com/01-asynchronous-iteration-patterns.html
I am a big fan of https://github.com/caolan/async which provides an async.each that applies an iterator to each element in parallel. This would likely suit your purpose.
来源:https://stackoverflow.com/questions/31304629/mongoose-find-call-inside-for-loop-using-a-latch