Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for the first await to complete before second await -Async/await

I am trying to make the second function to wait until the completion of the first. In the following example, I am not able to achieve it. When exploring about async/await, it was said that the order of execution would be sequential. However, this does not seem to be the case here.

function one() {
  setTimeout(() => {
    console.log('Hi')
  }, 5000)
}

function two() {
  setTimeout(() => {
    console.log('Bye')
  }, 2000)
}

async function doAll() {
  await one();
  await two();
}
async function demo() {
  await doAll();
}

demo()

Output

Bye
Hi

In this example, since function two involves less time, 'Bye' is printed before the 'Hi'. But I am trying to make sure when the first function completes its execution, then it should go to the second.

like image 347
Sathya Narayanan GVK Avatar asked Oct 17 '25 07:10

Sathya Narayanan GVK


1 Answers

That's because functions that you defined can't be await ed in a sense that they do not return a promise, that can resolve. Instead they complete instantly/"resolve" instantly.

function one() {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('Hi')
      resolve();
    }, 5000)
  })
}

function two() {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('Bye')
      resolve();
    }, 2000)
  })
}

async function doAll() {
  await one();
  await two();
}
async function demo() {
  await doAll();
}

demo()
like image 102
Krzysztof Krzeszewski Avatar answered Oct 19 '25 22:10

Krzysztof Krzeszewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!