嵌套mongoose函数完成之前的循环完成

所有,我正在写post函数,其中包括三个嵌套mongoose函数(findOne,findById&创build)的for循环。 但是,看起来function在完成下一个“i”之前还没有完成。 事实certificate,这个代码的console.log永远不会等于5.我已经做了大量的研究,并且明白这个问题是这些mongoose函数是asynchronous的,但是我还没有遇到过这样的问题:有三个嵌套函数,如下所示。 有什么办法可以让循环中的函数完成之前?

谢谢!

为了简单起见,我把i <5,尽pipe这是代码中的一个variables。 此外,让我们假设价格大于卖出是价格。

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 } 

根据上面的情况,我所理解的是,你想访问某个状态的函数之外的某个variables,就好像这些函数是同步执行的一样。

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

我正在写一个小代码,这将帮助你理解这个概念。

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

由于所有这些调用都是asynchronous的,它将基本上一次完成,并且不会等待任何一个部分完成。 因此,这可能是无序的。 对我来说,更容易把它看成是一堆不同的线索。 如果您需要按顺序运行,则可能必须基本上pause该部分上的asynchronous部分。