DEV Community

Discussion on: Asynchronous Programming in Node

Collapse
 
pspi profile image
Panu Pitkamaki

The inner workings of asynchronicity are worth learning! You'll need the knowledge as soon as you have to debug something that isn't working as you expected.

It's because of the way JavaScript works; it prioritizes non-asynchronous code in the event loop.

I'd reword this a bit. Think of the event-loop as a giant while loop that sits right outside of user code. When you let execution reach the end of the initial user code, it's the event-loop that you're returning control back to. When you've registered timers or made I/O calls, you've registered pieces of code that are to be called when the system clock reaches certain time or the CPU gets notified a peripheral device has responded.

Every piece of JavaScript is always run to completion. Nothing gets interrupted mid-way (pre-empted). The piece of code has to return control back to the system (e.g. by awaiting, yielding, returning from top-level function). Only then can the event-loop keep pumping and calling other pieces of JavaScript.

So, instead of saying "event-loop prioritizes non-asynchronous code" you could say "event-loop runs JavaScript to completion."