承诺{<pending>}&#39;为什么还有待处理?&#39;我该如何解决这个问题?

时间:2018-02-09 14:52:56

标签: 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 } ]

但我如何修复该承诺待处理部分,它是我在代码底部运行的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?');

2 个答案:

答案 0 :(得分:0)

替换:

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

使用:

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

run();

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

举一个简单的例子:

&#13;
&#13;
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();
&#13;
&#13;
&#13;

答案 1 :(得分:0)

因为你是console.log直接没有await的 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!!!!')
})()