Home > front end >  async/await vs callback resolution order, given shared asynchronicity
async/await vs callback resolution order, given shared asynchronicity

Time:05-22

If async/await & callbacks are both asynchronous, why are async/await resolved before callbacks?

For example (hypothetical, in practice its obviously not so cut-and-dry)

// classic callback
doSomething("./some-path", (err, data) => {...})

// This resolves with higher priority
await someAsyncFunction()

CodePudding user response:

In short, callbacks go to the end of the line in the regular job queue. async/await goes through the message queue, which is akin to a "fast pass" lane at an amusement park.

This article has some great examples and does a pretty good job covering this exact topic.

CodePudding user response:

Resolved/Rejected promises flow through the PromiseJobQueue and that queue is serviced BEFORE other items in the event loop such as file I/O completion callbacks or network completion callbacks or timers.

So, if you have a promise that is getting resolved in some manner that does not use a callback in the event loop (which is generally not the case), then it can get serviced in a higher priority way than other event loop-based callbacks.

But, if you build up a complex function that returns a promise and inside that complex function, you're using I/O callbacks in your own code in order to resolve/reject the promise, then you won't see that "fast lane" effect from the promise because it doesn't get resolved until the event loop services its callback anyway.

  • Related