tlt
tlt

Reputation: 15301

does async/await nesting have performance consequences?

lets consider we have N async functions like:

async function1(){
  return await fetch(...);
}
.
.
.
async functionN(){
  return await fetch(...);
}

then we have a function like:

async wrapper(){
   let var = await fetch(...);
   function1();
   .
   .
   .
   functionN();
}

would this create one big microtask queue that would effectively block ui thread going to next task before all called functions resolved their awaits?

Upvotes: 2

Views: 130

Answers (1)

trincot
trincot

Reputation: 351384

There is nothing in the microtask queue until promises resolve. Until then other tasks and (UI) events can be processed.

This is because the await operator will make the corresponding async function return immediately, allowing other JS code to execute. In your case the promise is returned by fetch, which in practice will not resolve immediately. So there is nothing blocking here.

Then when the HTTP response makes the fetch promise resolve, a microtask will indeed be created, which, when when executed will restore the corresponding async function's execution context. Your example function has nothing else to do, so that is quickly done.

Note that it does not matter whether this function was originally called from within some other function: at this stage, only that particular function's execution context (in which an awaited promise resolved) is restored without any pre-existing callstack. So it does not return again to the wrapping function. That already happened in the first phase and will not happen again.

Then again there is free event processing until the next fetch promise resolves. And so it continues.

Upvotes: 4

Related Questions