javascript - Promise { <pending> } ' why is it still pending?' 我该如何解决这个问题?

标签 javascript node.js mongodb sockets response

因此控制台中的结果显示为 -

Promise { <pending> } ' why is it still pending?'
[ { _id: 5a7c6552380e0a299fa752d3, username: 'test', score: 44 } ]

所以它告诉我 Promise { pending } 但随后是我想看到的答案 -

[ { _id: 5a7c6552380e0a299fa752d3, username: 'test', score: 44 } ]

但是我该如何修复那个 promise pending 部分,它是我在代码底部运行的 console.log。

function resolveAfter1() {
  return new Promise((resolve, reject) => {
    var scoresFromDb = db.account.find({}, { username: 1, score: 1 }).toArray(function(err, result) {
          if (err) 
              reject(err);
          else
              resolve(result);
    });
  });
}

resolveAfter1() // resolve function
    .then((result)=>{console.log(result);})
    .catch((error)=>{console.log(error);})

    async function asyncCall() {
      var result = await resolveAfter1();
      // console.log(result);
    }

    console.log(asyncCall(), ' why is it still pending?');

最佳答案

替换:

console.log(asyncCall(), ' why is it still pending?');

与:

async function run() {
   console.log(await asyncCall());
}

run();

您正在打印 asyncCall 的结果,这是一个 async function。异步函数将返回的结果包装在 Promise 中,如果您想要 Promise 解析到的实际值,则必须使用 await someAsyncFunc()

举个简单的例子:

async function asyncCall() {
   return 1;
}

async function run() {
   console.log(asyncCall()); // this doesn't wait for the Promise to resolve
   console.log(await asyncCall()); // this does
}

run();

关于javascript - Promise { <pending> } ' why is it still pending?' 我该如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48708449/

相关文章:

javascript - 搜索因输入 onBlur 而停止

javascript - 如何创建可与嵌入代码一起使用的按钮?

javascript - 如何确定焦点何时离开 HTML 表单(即表单的子项不再具有焦点)?

javascript - 读取嵌套对象中的嵌套对象

mongodb - 在 mongo 中的日期之间的数组中查找

mongodb - 在 MongoDB Spring Data 中使用多个方面

spring - Cloudfoundry Spring MongoDB 示例应用程序部署失败

javascript - ChartJS 3.8.0 堆叠条形组合标签

node.js - 为我的 Meteor 应用程序的生产实例传递配置文件?

javascript - 使用map 进行并行请求,使用promise.all 进行for 循环,然后