【发布时间】: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