Muhammad Naufil
Muhammad Naufil

Reputation: 2647

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

Upvotes: 10

Views: 14580

Answers (3)

Mir-Ismaili
Mir-Ismaili

Reputation: 17184

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


In Bun.js, use sleep:

// sleep for 1 second
await Bun.sleep(1000)

See: https://bun.sh/guides/util/sleep

Upvotes: 2

Yousaf
Yousaf

Reputation: 29344

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

Upvotes: 15

Rahul Beniwal
Rahul Beniwal

Reputation: 687

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.

Upvotes: 4

Related Questions