Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does javascript "await" pauses immediately whatever it is doing and resumes the async function once a promise is resolved?

I just started learning async-await and just want to know the program execution flow clearly.

async function A() {
 await doSomethingAsync();
 doThisNext();
}

A();
B();
C();

Given that above code snippet, let's say B() is being executed at the moment.

  1. While B() is executing and if doSomethingAsync() gets resolved right at that moment, will the programing execution suspends B() temporarily to resume A() (ie; start doThisNext() and then switch back?

  2. Or will B() (or even C()) be finished up first and then executes doThisNext()?

  3. Or I am misunderstanding the whole thing?

Assume B and C are just generic functions with no async code.

like image 962
Aung Khant Avatar asked Nov 26 '25 05:11

Aung Khant


1 Answers

While B() is executing and if doSomethingAsync() gets resolved right at that moment, will the programing execution suspends B() temporarily to resume A() (ie; start doThisNext() and then switch back?

This is not how event loop works. If B is synchronous it wont be interrupted by promise resolution. Which is scheduled to be executed during current promise resolution micro-queue.

So, the order will be

  1. A started and suspended
  2. B ended
  3. C ended
  4. A resumed and ended

A();
B();
C();



async function A() {
  console.log('A start');
  await delay(0);
  // or even
  // await Promise.resolve('done')
  console.log('A end')
}

function B() {
  console.log('B')
}

function C() {
  console.log('C')
}

function delay(ms) {
  return new Promise(r => setTimeout(r, ms))
}
like image 171
Yury Tarabanko Avatar answered Nov 27 '25 20:11

Yury Tarabanko



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!