Boris Grunwald
Boris Grunwald

Reputation: 2712

Trying to understand async await

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?

Upvotes: 0

Views: 57

Answers (1)

Quentin
Quentin

Reputation: 943193

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

Upvotes: 5

Related Questions