Search code examples
node.jsasynchronouspromiseasync-await

await setTimeout is not synchronously waiting


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

Solution

  • setTimeout doesn't return 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();