嵌套的Mongoose异步函数

时间:2014-08-12 14:47:29

标签: javascript node.js asynchronous mongoose q

我需要迭代一个数组来寻找项目,然后对这些价格求和。

这是异步功能的问题。我用Q来帮助我承诺,但我无法解决这种情况。

var price = 0;

var setPrice = function() {
    _.each(order.items, function(item) {
        Item.findOne({ 'shortname': item.item }).exec().then(function(doc) {
            price += doc.price;
        });
    });
}

Q.nfcall(setPrice).then(function() {
    console.log(price);
}

价格设置为0,nfcall运行setPrice函数迭代并汇总价格,然后,“then”函数应显示总价格,但事实并非如此。

我该如何解决这种情况?

1 个答案:

答案 0 :(得分:0)

不要一个接一个地找到它们,为什么不一次归还所有这些。

Item.where('shortname'.in(order.items).execute(function(err,docs) {
  //in here you can do your summation, and the rest of your code. 
  var price = 0;
  for(var i=0;i<docs.length;i++) {
    price += docs[i].price;
  }
});