Mongoose find() call inside for loop using a latch

梦想的初衷 提交于 2020-01-04 13:27:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!