因此控制台中的结果显示为 -
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/