await setTimeout is not synchronously waiting

Viewed 2804

I know that setTimeout is an API which runs asynchronously and I wanted to run it synchronously. Using async/await like below should print bla bla first but I get bla first.

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

setTimeout doesn't returns a Promise, so you can't await it.

You can wrap setTimeout in a function that returns a Promise which is fulfilled once the timer expires. You can await this wrapper function.

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

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

Please support with answered if it solved your problem, thanks.

Related