Aditya Patnaik
Aditya Patnaik

Reputation: 1776

Why does the control goes back to the caller function after the execution of the first await statement in an async function?

Here's the code:

function B() {
  return 'B';
}

async function test(b) {
  await console.log('Z')
  await console.log(b())
  console.log('X')
  await console.log("hihihi")
}

console.log('A');
test(B);
console.log('C');
console.log('P');

This output's to A Z C P B X hihihi

Question is:

Upvotes: 0

Views: 149

Answers (2)

Benjaco
Benjaco

Reputation: 303

When a promise is done, any further execution is going into a queue there is executed after the code there is running at the moment,

first, console.log('A') is called as normal

then console.log('Z') is called as normal, but javascript is exception a promise, but it is fine for it to take a normal statement, but any code after the call stack is been emptying

then c and p is logged

now the callstack is empty, and now its time for evaluating the microtask queue

b is called. and another microtask is carried out

x is logged normal

hi hi hi is logged, and another microtask is started, but then the function exits

I really do recommend watching "the event loop" which goes into details with this functionality https://www.youtube.com/watch?v=cCOL7MC4Pl0 done by Jake which also have an article on it https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/

everthing is called on the same thread, see richytong's code block for your 2nd question

Upvotes: 1

richytong
richytong

Reputation: 2452

Right now, your single node thread sees an order of execution that looks like this

console.log('A') // > A
test(B) // oh okay, looks like an async function call. i'll start this off and move on
console.log('C'); // > C
console.log('P'); // > P

When test(B) is called, another "thread" of sorts handles the execution. This is all because test is an async function, so every operation inside that function is handled a bit differently than a regular synchronous function.

If you want them all to appear in order, you can use another async function and await test(B)

function B(){
  return 'B';
}

async function test(b){
  await console.log('Z')
  await console.log(b())
  console.log('X')
  await console.log("hihihi")
}

async function main() {
  console.log('A');
  await test(B);
  console.log('C');
  console.log('P');
}

main()

All of this is pretty useful because of a nodejs thing called non-blocking io. Here's a question that could shed some light on that.

Here is node's very own explanation of the event loop, which is a key concept for understanding non-blocking io

Upvotes: 2

Related Questions