猫鼬find()使用闩锁在内部调用循环 [英] Mongoose find() call inside for loop using a latch

查看:77
本文介绍了猫鼬find()使用闩锁在内部调用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经研究了几个小时,似乎找不到答案. 问题是我在for循环中有对mongoDB的调用.我使用的是闩锁,因此for会先等待通话结束,然后再继续前进.这是我的代码:

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;
}

问题是它甚至没有运行Table1.find()的回调,而是在一段时间内被阻塞. 有人可以帮我吗?

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?

推荐答案

for循环永远不会越过while循环(因为您已经创建了无限循环).

The for loop will never proceed past the while loop (as you've created an infinite loop).

有多种方法可以处理节点循环中的异步代码,包括函数外部的计数器变量和尾递归.您可以在此处查看一些示例: http://metaduck.com/01-asynchronous-iteration-patterns.html

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

我非常喜欢 https://github.com/caolan/async 一个async.each,它并行地将迭代器应用于每个元素.这很可能适合您的目的.

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.

这篇关于猫鼬find()使用闩锁在内部调用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆