0

I'm trying to understand why this piece of code doesn't behave as I expect:

async function test() {
  await setTimeout(() => {
    console.log('done')
  }, 1000)

  console.log('it finished');
}


test();

This first prints it finished and then prints done afterwards. Shouldn't this code wait for the timeout to finish before executing console.log('it finished'); or have I misunderstood something?

Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
Boris Grunwald
  • 2,602
  • 3
  • 20
  • 36
  • why are you using `await` on `setTimeout`? it's not a promise – Tibebes. M Oct 29 '20 at 11:50
  • you should have a look at promises and how they work in general – EugenSunic Oct 29 '20 at 11:56
  • 1
    Does this answer your question? [How to setTimeout on async await call node](https://stackoverflow.com/questions/50091857/how-to-settimeout-on-async-await-call-node) And Maybe the title should be like _Trying to await setTimeout not working_ – Ulysse BN Oct 29 '20 at 11:57

1 Answers1

5

You can only usefully await a promise.

setTimeout returns a timeout id (a number) that you can pass to clearTimeout to cancel it. It doesn't return a promise.

You could wrap setTimeout in a promise…

async function test() {
  await new Promise( resolve => setTimeout(() => {
    console.log('done');
    resolve("done");
  }, 1000));

  console.log('it finished');
}


test();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335