【问题标题】:Loop finishing before nested mongoose functions complete在嵌套的 mongoose 函数完成之前完成循环
【发布时间】:2017-06-10 03:29:05
【问题描述】:

所有,我正在编写一个 post 函数,其中包含一个带有三个嵌套 mongoose 函数(findOne、findById 和 create)的 for 循环。然而,在进入下一个“i”之前,这些功能似乎还没有完成。这段代码的 console.log 从不等于 5 的事实证明了这一点。我进行了大量的研究并理解问题是这些 mongoose 函数是异步的,但我还没有遇到过人们的问题具有如下三个嵌套函数。有什么方法可以让函数在循环进行之前完成?

谢谢!

为简单起见,我将 i

var quantity = 0;
if(price >= sellYesPricesMin){
    for (i = 0; i < 5; i ++){
        if(price >= sellYesPricesMin && sellYesPricesMin>0){
            Order.findOne({"yes_or_no":"NO", "buy_or_sell":"BUY","event.id":req.params.id},function(err, foundOrder){
                if(err){
                    console.log(err);
                } else {
                    User.findById(foundOrder.author.id, function(err, foundUser){
                        if(err){
                            console.log( err);
                        } else {
                            Share.create({}, function (err, newShare) {
                                if (err){
                                    console.log(err);
                                    quantity = quantity + 1;
                                    sharesCreated++;   
                                    campground.shares.push(newShare);    
                                    campground.save();
                                    foundUser.save();
                                }
                            });
                        }
                    });
                }
            });
        } else {    
            campground.buyYesPrices.push(parseFloat(Math.round(price * 100) / 100).toFixed(2));            
            req.user.save();
            campground.save();
        }
        req.user.save();
        campground.save();
    }
    console.log("QUANTITY: " + quantity);
} else {
    // BLAH BLAH BLAH
}

【问题讨论】:

  • 所有这些函数都是异步的,Node不会等待它完成,它会移动到下一个函数。

标签: javascript node.js mongodb asynchronous mongoose-populate


【解决方案1】:

根据上面的场景,我的理解是你想在一个状态下访问函数之外的某些变量,就好像这些函数是同步执行的一样。

您可以将这些变量绑定到这些函数,这些执行将按照您希望它们执行的方式进行。

我正在编写一个小代码来帮助您理解这个概念。

for (var i = 0; i < 10; i++) {

    asynccall("Hello", function (others, err, data) {
        console.log("Others is same as i in synchrnous call " + others);
    }.bind(this, i));
}

【讨论】:

    【解决方案2】:

    由于所有这些调用都是异步的,它基本上会一次完成所有这些,它不会等待任何一个部分完成。因此,它可能是无序的。对我来说,更容易将其视为一堆不同的线程。如果您需要按顺序运行,您可能必须基本上 pause 这一节的异步部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-28
      • 1970-01-01
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多