【发布时间】:2021-08-16 23:56:29
【问题描述】:
我尝试组合两个函数值(来自a() 和b()),但代码没有像预期的那样等待函数test 中的等待语句。相反,结果值直接打印错误的结果。
function resData(status, message) {
return { ok: status, message: message };
}
function a() {
return resData(true, 'A');
}
async function b() {
// simulate some long async task (e.g. db call) and then return the boolean result
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
}); }
await sleep(2500);
return resData(true, 'B');
}
async function isValid() {
const promises = [a, b].map(async (fnc) => { return await fnc().ok; });
const results = await Promise.all(promises);
// combine the results to one boolean value
return results.every(Boolean);
}
async function test() {
// not waiting here
const res = await isValid();
// prints directly - wrong result false
console.log('result', res);
}
test();
在错误的结果输出后等待 2.5 秒。我认为这与 resData 的函数调用有关,但我自己无法弄清楚,我的 async / await 误解在哪里。提前致谢。
【问题讨论】:
-
await fnc().ok->(await fnc()).ok否则你只是在等待undefined,因为fnc()返回一个承诺,.ok在该承诺上返回undefined。
标签: javascript node.js async-await