【问题标题】:node/mongo response after loop循环后的节点/mongo响应
【发布时间】:2017-01-09 18:36:37
【问题描述】:

当循环完成后,我如何将总数返回为 resolve(total)?

怎么做?

function getTotalAttack(minions) {
    return new Promise( function (resolve, reject) {
        console.log("starting do the totalattack math");

        var total = 0;
        for(var minion in minions) {
            console.log("sending one now");

            minions.findOne({ _Id  : minion }).then(function(response){
                total = total + response.attack;
            });

        }
        console.log("result is " + total);
        return resolve(total);
    });
}

【问题讨论】:

    标签: node.js mongodb promise


    【解决方案1】:

    你从

    发出另一个异步调用
    minions.findOne({ _Id  : thisminion }).then( function(response){
                total = +total + response.attack;
            });
    

    您应该一次性获取所有 ID。 我想你在这里使用 mongodb? 使用 $in 那么你就不需要for循环了。

    mongodb $in

    【讨论】:

      【解决方案2】:

      您可以使用Promise.all()

      function getTotalAttack(minionsIds) {
          return new Promise( function (resolve, reject) {
      
              var total = 0,
                  queries$p=[]
              // if you need only to retrieve the documents :
              // queries$p = minions.find({_id:{$in:minionsIds}}).exec()
      
              // or if you need an extra instruction in between :
              minionsIds.forEach(function(mids) {
                  console.log("sending one now");
                  queries$p.push(minions.findById(mids).exec())
              });
      
              Promise.all(queries$p)
               .then( function(minions) { 
                  minions.forEach(function(minion){ 
                      total += minion.attack;
                  })
                  console.log("total attack:", total);       
                  return resolve(total)
               })
               .catch( function(e) {
                  return resolve(0)
               })
               ;
          });
      }
      

      来自 MDN:

      如果其中一个元素被拒绝并且 Promise.all 被拒绝并且 Promise.all 快速失败:如果您有四个承诺在之后解决 超时,一个立即拒绝,然后 Promise.all 拒绝 马上。

      【讨论】:

      • 当输入中的每个数据都是 _id 时,查询会如何?就像我的代码查询一样?
      • 在 var minion 中结果为 0
      • JS 的一个常见缺陷:for var i in A 不返回 A 的元素,而是返回它们的索引。
      • 你能改变,如果查询中存在任何 ids,它返回 0;?当我传递不再存在的 id 时,导致我现在遇到问题。
      【解决方案3】:

      如果您正在寻找所有小兵攻击的总和,您也可以直接使用 mongo 在一个聚合中执行它:

      minion.aggregate(
         [{
            $group:{
              _id: null, 
              total:{$sum:"$attack"}
            }
         }]
      ).then( etc.. )
      

      【讨论】:

      • 是的,但只有我有 ID 的人才会被求和
      • 它们都在 db 中,但我只想获取我变量中的 ID 的总和
      • 那你只需要在``{$group:...}``之前加一个{$match: { _id: { $in: minionsIds} }}就行了
      • 但是我需要做一个循环,因为我最多有 5 个 id。
      • 无循环:提供数组,返回总和。
      猜你喜欢
      • 1970-01-01
      • 2014-08-02
      • 2021-04-26
      • 2012-08-10
      • 2014-09-06
      • 2012-05-02
      • 2019-08-18
      • 1970-01-01
      • 2017-07-12
      相关资源
      最近更新 更多