NodeJS await setTimeout未同步等待

qyzbxkaa  于 2023-04-05  发布在  Node.js
关注(0)|答案(2)|浏览(325)

我知道setTimeout是一个异步运行的API,我想同步运行它。像下面这样使用async/await应该先打印bla bla,但我先得到bla

async function testing(){
    console.log("testing function has been triggered");
      await setTimeout(function () {
        console.log("bla bla")
      }, 4200)
    console.log("bla");
  }
js81xvg6

js81xvg61#

setTimeout不返回Promise,所以你不能await它。
你可以将setTimeout Package 在一个函数中,该函数返回一个Promise,一旦计时器到期,该函数将被执行。你可以将这个 Package 函数 Package 为await

function createCustomTimeout(seconds) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log('bla bla');
      resolve();
    }, seconds * 1000);
  });
}

async function testing() {
  console.log('testing function has been triggered');
  await createCustomTimeout(4);
  console.log('bla');
}

testing();
rmbxnbpk

rmbxnbpk2#

async function testing(){
  console.log("testing function has been triggered");
   console.log(await printFunction());
  console.log("bla");
}

function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

const printFunction = async () => {
  await timeout(4200);
  return "bla bla"
}

testing();

如果解决了您的问题,请支持并回答,谢谢。

相关问题