【问题标题】:Nested Mongoose asynchronous functions嵌套的 Mongoose 异步函数
【发布时间】:2014-10-05 16:52:14
【问题描述】:

我需要在一个数组中进行迭代以查找商品,然后对这些价格求和。

这是异步函数的问题。我正在使用 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);
}

Price 设置为 0,nfcall 运行 setPrice 函数对价格进行迭代和求和,然后“then”函数应该显示总价格,但它没有。

我该如何解决这种情况?

【问题讨论】:

  • 看看使用aggregate,而不是让 MongoDB 在单个查询中为您计算总价。

标签: javascript node.js asynchronous mongoose q


【解决方案1】:

与其一一寻找,不如一并归还。

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

【讨论】:

    猜你喜欢
    • 2012-10-12
    • 2019-10-02
    • 2021-02-04
    • 1970-01-01
    • 2017-09-05
    • 2014-06-23
    • 2018-10-28
    • 1970-01-01
    相关资源
    最近更新 更多