等待setTimeout不同步等待

时间:2020-08-16 16:23:46

标签: node.js asynchronous promise async-await

我知道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");
  }

2 个答案:

答案 0 :(得分:1)

setTimeout不会返回Promise,因此您无法await

您可以将setTimeout包装在一个返回Promise的函数中,一旦计时器到期,该函数就会完成。您可以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();

答案 1 :(得分:1)

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();

如果它解决了您的问题,请给予支持,谢谢。