【问题标题】:Promise { <pending> } ' why is it still pending?' How can I fix this?Promise { <pending> } '为什么它还在等待中?我怎样才能解决这个问题?
【发布时间】:2018-07-20 09:04:58
【问题描述】:

所以控制台中的结果显示为 -

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

所以它告诉我 Promise {pending } 但随后给出我想查看的答案 -

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

但是我怎样才能修复承诺待定部分,它是我在代码底部运行的 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?');

【问题讨论】:

标签: javascript node.js mongodb sockets response


【解决方案1】:

替换:

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

【讨论】:

  • 这让我不确定,不知道为什么。
【解决方案2】:

因为你是console.log一个AsyncFunction直接没有等待,它会返回给你一个未解析的Promise对象

function resolveAfter1() {
  return new Promise((resolve, reject) => {
    setTimeout(resolve('a'), 100)
  })
}

async function asyncCall() {
  var result = await resolveAfter1();
  return result
}

(async () => {
  console.log(await asyncCall(), ' It is not pending anymore!!!!')
})()

【讨论】:

    猜你喜欢
    • 2013-10-24
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2019-11-07
    • 2012-03-16
    • 1970-01-01
    • 2015-04-08
    • 2020-11-28
    相关资源
    最近更新 更多