8

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");
  }
Muhammad Naufil
  • 2,420
  • 2
  • 17
  • 48
  • `await` only does anything useful when you `await` a promise. Since `setTimeout()` does not return a promise (it returns a timerID), your `await` does nothing at all here. You can wrap `setTimeout()` in a small function that returns a promise that resolves when the timer fires and use that wrapper instead. That still won't be synchronous in the true sense of the word, but the function execution would be internally paused. – jfriend00 Aug 16 '20 at 16:27

3 Answers3

11

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();
Yousaf
  • 27,861
  • 6
  • 44
  • 69
3
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.

Rahul Beniwal
  • 639
  • 4
  • 9
0

Import setTimeout from node:timers/promises:

import {setTimeout} from 'node:timers/promises'

const res = await setTimeout(1000, 'result')

console.log(res) // Prints 'result' after 1000ms

See: https://nodejs.org/api/timers.html#timers-promises-api

Mir-Ismaili
  • 13,974
  • 8
  • 82
  • 100