How does javascript async/await actually work?

You have to read the quoted part slightly differently:

An async function can contain an await expression that pauses the execution of the async function

Just the async function itself pauses execution, the function that called it goes on then.

If you think of a synchronous callstack, what happens is that the asynchronous functions context gets popped of, and stored somewhere else:

 stack: [init] -> [async] fun1 -> sleep -> setTimeout
  // The promise gets returned from sleep
 stack: [init] -> [async] fun1
 // The async function gets popped of
 stack: [init]
 hidden: [async] fun1
 // synchronous execution ends
 stack: -
 hidden: [async] fun1
 // the timer triggers, the promise gets resolved
 stack: setTimeout callback
 hidden: [async] fun1
 // synchronous execution ends
 stack: -
 hidden: [async] fun1
 // the promise resolves, the async fun1 context gets moved onto the stack
 stack: [async] fun1

It seems fun1 returns at the “await” line

Yes, exactly. In that moment it returns a promise, that resolves when the async function returns (after it continued execution somewhen).

And it seems I never get the return value of fun1(“returnfromfun1”).

You can get it when the promise resolves:

  fun1().then(result => console.log(result));

Leave a Comment