为什么await不等待

Viv*_*odi 1 javascript

如何先等待setTimeout完成

function a() {
  setTimeout(() => {
    console.log('should wait');
  }, 5000);
}
async function b(c) {
  console.log('hello');
  await c();
}
b(a);
console.log('out');
Run Code Online (Sandbox Code Playgroud)
我的预期输出是

你好

应该等待

出去

Som*_*jee 5

setTimeout不返回 Promise,await仅适用于 Promise。

另外,将其放在函数console.log("out")内部b,使其在a函数之后运行。

检查下面的代码片段,它满足您的要求。

function a() {
  return new Promise((res, rej) => {
    setTimeout(() => {
      console.log('should wait');
      res();
    }, 5000);
  })
}
async function b(c) {
  console.log('hello');
  await c();
  console.log('out');
}
b(a);
Run Code Online (Sandbox Code Playgroud)