【问题标题】:For loop not updating array from mongoose callbackFor循环不从猫鼬回调中更新数组
【发布时间】:2019-03-06 15:11:10
【问题描述】:

我认为我的问题在于 JS 的异步特性。我正在尝试将项目推送到数组中,但它似乎没有更新它......我在 for 循环中做了 console.log 语句,并看到它用数字填充数组,但是当我 console.log循环外的数组,我得到一个空数组。我正在使用猫鼬。 有什么建议吗?

代码如下:

let collections = [];
                return Promise.all(courts.map(court => {
                  return new Promise((resolve, reject) => {
                    return Promise.all(court.users.map(async user => {
                      let tempPromise = new Promise((resolve, reject) => { 
                          setTimeout(() => {
                              resolve();
                          }, 5000);
                      });
                                  return SignDetail.find({
                                    userName: user.userName,
                                    signStatus: "signIn",
                                  }).then(function(sign) { 
                                    if (user.userName.endsWith('zs')) { 
                                        let signCount = 0;
                                        if (sign.length > 1) {
                                            for (let j = 0; j < sign.length; j++) {
                                                let courtObj = {courtName: sign[j].userName}; //make court object
                                                signCount++; //increment each time there's a signature
                                                if (j === sign.length - 1) { //only push object in array when all signatures have been counted
                                                    courtObj.signCount = signCount;
                                                    collections.push(courtObj);
                                                    console.log(collections)
                                                } 
                                            }
                                        } 

                                    } //end here
                                  }); 
                      return tempPromise;
                    })).then(_ => resolve(collections));
                  })
                })).then(collections => {
                  // HERE you will your collection and you can use this promise where this function is being called. 
                  console.log(collections);
                });

【问题讨论】:

    标签: javascript mongoose


    【解决方案1】:

    函数SignDetail.find()是异步函数,不能同步返回res.render。您需要从此函数返回一个承诺,该承诺将解析为所需的输出。

    你可以这样做。

    let collections = [];
    return Promise.all(courts.map(court => {
      return new Promise((resolve, reject) => {
        return Promise.all(court.users.map(oUser => {
          var tempPromise = new Promise();
          if(oUser.userName.endsWith('zs')){
            SignDetail.find(
              {username: oUser.username. signStatus: 'signIn'}, 
              function(err, sign){
                collection.push(sign.length);
                tempPromise.resolve();
              })
          } else{
             tempPromise.resolve();
          }
          return tempPromise;
        })).then(_ => resolve());
      })
    })).then(_ => {
      // HERE you will your collection and you can use this promise where this function is being called. 
      console.log(collections);
    });
    

    【讨论】:

    • 您好,感谢您的快速回复。当我将此代码放入我的 else 块时,我收到一条错误消息:未处理的承诺拒绝警告:无法读取未定义的属性映射“”
    • 我刚刚编辑了它。将 court.user.map 更改为 court.users.map
    • 你好。我想知道为什么我的代码将集合输出为数组的数组,因为有很多次。比如在promise里面,当我们collections.push(courtObj)时,console.log只输出1个item,但是在后面的console.log中,如果有10个court,我们会得到一个带有courtObj 10次的数组....问题是用resolve(collections),但我不知道如何让它只输出正确的原始集合数组。解析后的集合数组示例:[ [ { courtName: '1100zs', signCount: 9 } ], [ { courtName: '1100zs', signCount: 9 } ]
    • 这是因为 let collections = [] 是在 court.users.map 中完成的,它为每个 court.users 创建了新数组。我编辑了它。请立即检查。
    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 1970-01-01
    • 2016-11-01
    • 2015-01-27
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    相关资源
    最近更新 更多