首页 > 解决方案 > 承诺解决对象给空对象

问题描述

所以在我的节点文件中,我从 Mongoose 数据库中获取一些数据,执行一些操作,最后我想要一个像对象一样的字典。现在我的 Mongoose 数据库只有两个我想要的对象,所以我使用aggregate命令给我那些。然后,我遍历结果,并将它们添加到字典中。然后,我想从字典中显示一些东西。由于这一切的异步性质,我被迫学习/使用 Promise。因此,这是我生成的代码:

function f1(){
    return new Promise(resolve=>{    
        collectionName.aggregate([
        {
            $group:
                {
                _id: "$ids",
                property: {$max: "$properties"}
                }
            }
    ]).then(data=>{
        for(i=0; i<data.length; i++){
            dictionary[data[i]['_id']] = data[i]['property'];
        }
    });
    resolve(dictionary);
    });

    };

async function f2(){
    var dict = await f1()
    console.log(dict)

f1();
f2();

当我将 console.log 放入 for 循环时,我得到了我想要的数据,因为它具有字典形式的 id 和属性。但是,当我运行 f2 时,我只得到{}输出。有谁知道为什么?

标签: javascriptpromise

解决方案


由于在resolve(dictionary)' aggregate()s之外then(),它在填充之前执行dictionary,因此是空对象。尝试将to 移到ofresolve(dictionary)内部,以返回值为 的承诺。实际上,您正在尝试链接 promises。确保也将整体返回,以确保从 . 中返回整个承诺。then()aggregate()dictionarycollectionName.aggregate()f1()

function f1() {
  return new Promise(resolve => {
    return collectionName.aggregate([{
      $group: {
        _id: "$ids",
        property: {
          $max: "$properties"
        }
      }
    }]).then(data => {
      for (i = 0; i < data.length; i++) {
        dictionary[data[i]['_id']] = data[i]['property'];
      }

      return resolve(dictionary);
    });
  });
}

希望这会有所帮助!


推荐阅读