DEV Community

Zack
Zack

Posted on

Asynchronous Programming in Node

Hello, everyone! I thought I'd go over a pretty interesting topic, which is asynchronous programming.

The programming language we'll be using is JavaScript (Node), of course.

An Explanation

The setTimeout function in JavaScript calls a function after a certain amount of time in an asynchronous fashion. We're going to use this inbuild function to our advantage.

Let's first create a wrapper function:

let wrapper = function(func) {
    setTimeout(func, 0);
}

Nice, so all we need to do now is to call the function with a function as the first argument:

let wrapper = function(func) {
    setTimeout(func, 0);
}

wrapper(() => console.log('Hello, world! (1)'));
console.log('Hello, world! (2)');

Now if you run it, the output should be like this:

Hello, world! (2)
Hello, world! (1)

Why is Hello, world! (2) shown first? It's because of the way JavaScript works; it prioritizes non-asynchronous code in the event loop.

There's a great video by Fireship that explains it a bit better: link

Top comments (2)

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."

Collapse
 
fly profile image
joon

youtu.be/8aGhZQkoFbQ?t=894

I greatly recommend watching the whole video for a relatively quick yet deep understanding of the event loop, but watching from here explains your post beautifully as well :)