Syed Habib M
Syed Habib M

Reputation: 1817

async/await nodejs funciontality

I have following code snippet with async/await.

async function test1 () {
  setTimeout(() => {
    console.log("1")
  }, 2000);
}

async function test2 () {
  setTimeout(() => {
    console.log("2")
  }, 1000);
}

async function test3 () {
  setTimeout(() => {
    console.log("3")
  }, 1500);
}

async function test4 () {console.log("4")}

async function run () {
  await test1()
  await test2()
  await test3()
  await test4()
}

run()

When I explore above code snippet, I am expecting output as 1, 2, 3, 4. But I got 4, 2, 3, 1. Am I missed anything here?

Node Version v10.13.0

Upvotes: 1

Views: 36

Answers (1)

Estus Flask
Estus Flask

Reputation: 223064

awaiting test1, etc. is the same as awaiting setTimeout(...) directly. setTimeout is not promise-based and isn't taken into account in promise chain.

await test1(), etc. result in one-tick delays, run() promise resolves instantly.

In order for the code to work as intended, it should be:

function test1 () {
  return new Promise(resolve => setTimeout(() => {
    console.log("1");
    resolve();
  }, 2000));
}

test1, etc. don't need to be async because they cannot benefit from a promise created by async function.

Upvotes: 5

Related Questions