Node Async and Event Loop

Node and the entire JavaScript ecosystem relies on async and its the event loop management. The mastery of these topics gives you superpowers to write efficient Node code.

Learning Objectives

The event loop

Like in javascript, the world we live in is an indefinite event loop. The year starts by Jan. 1 ends by Dec. 31, only to begin the next day with Jan. 1 again. An unending cycle of days and months. With each day capturing amazing and disastrous events.

Javascript executes in a loop, the event loop. It is an infinite loop that waits for tasks, delivers them, then sleeps until it receives more tasks. It's like a worker who constantly checks for new jobs to do, completes them, and then sit waiting for the next one.

Thanks to this loop, Node can handle a lot of tasks on a single execution thread. Tasks run efficiently without creating multiple threads.

Understanding that a task may be sync or async

By default, Javascript runs in sync (not async) from top to bottom. This means when it reaches a line whose task takes a lot of time, the rest of the lines below it would wait for the heavy duty line to complete.

In contrast, when async, the Javascript engine would read the next lines without waiting until the heavy duty line complete. Although we have a single execution thread in JavaScript by default, with the async superpowers, Javascript can do many heavy duty task by directing them to the OS/Kernel then move to the next line after.

Node is async first.

What's async

Async is short for asynchronously. It is both a concept and keyword in Node ( and JavaScript).

Node associates async operations ( or tasks) with events. Whenever they are triggered, they are run independently from other non-async operations. And when done, it cedes control back to the execution event loop to handle.

Examples of async tasks ( or operations) are writing/reading a file, network fetches.

Explanation with some layman examples

For example, a tailor sewing all by her is synchronous. As a tailor, you can not stitch a cloth until you cut them. After cutting, weave ( depending on the material) before stitching and so on. Since it is just you, you can only do them one at a time.

A Baker, who bakes asynchronously. She starts by prepping the oven by herself. For mixing the flour & eggs, she pours them into a Mixer machine. Since this is handled by the Mixer, she won't have to wait before doing another thing. While the machine is mixing, she go get the cake cups, come back to get the mixed flour when the machine is done.

These scenarios represent Async and Sync well. Async guarantees your node program can keep running while another piece of the program is doing something else that usually takes time.

Async operations take handlers. These handlers can be expressed in 3 broad patterns: Callbacks, Promises (and Async/Await) and Listeners.

Callbacks

Before JavaScript gave us async by default, Node gave us Callbacks. Callbacks are functions that are called back in loop after an async task completes.

Imagine this, if the Mixer is done smoothing, a sound should peep.

bashMixer("be mixing", (err, done){
    if(!err){
        done(peep)
    }
})

Another example would be reading from the drive or filesystem. Until recently with faster computers, it takes a substantial time to read from the drive. You don't want to delay your entire program waiting for a feedback.

Synchronously reading a file

bashimport {readFileSync} from "fs";

let fileName
console.log("Hello")
// prints "Hello" -> GoToNextLine

fileName = readFileSync('file.txt')
// takes 10 secs -> after it is done reading file -> GoToNextLine

console.log(fileName)
// prints "FileName.txt" -> ends
Callback style

I make these mistakes myself so I think it is important to put a little more attention here.

When writing a callback function for an async operation in node, it is important to keep these two vital points in mind:

  1. Node's callback style is referred to as "error-first callback style". Callbacks must always have an error as its first argument.
  2. Callback functions would usually be the last argument for an async function.

Asynchronously reading a file

bashimport { readFile } from "fs";

let fileName
console.log("Hello")
// prints "Hello" -> GoToNextLine

readFile('file', cb(err, done)=> {}) // assume it takes 10 secs to read the file
// give the task to OS/Kernel -> GoToNextLine

console.log(fileName)
// prints undefined -> wait

//after 10sec
// cb() comes back
A little beyond: Async in series and parallel

Sometimes you want to make async operations for multiple things at a time. Say an array of items and need the results in order. This introduces the dilemma to either run async in series and parallel.

An example where this shine is trying to read all the files in a directory. You can either do this in series or parallel.

Async in parallel

bashfs.readdir('foldername', (err, files){
    if(err) throw new Error(err)
    files.forEach((f)=> {
        fs.readFile(f, (err, result){
            if(err){
              throw new Error(err)
            }
            console.log(result.length)
        })
    })
})

The log (result.length) can not be trusted because they are not in order.

The problem with running async operations in parallel is that results don't come in the order. To solve this, let's do in series instead.

Async in Series Recursively

bashfs.readdir("ddd", (err, files)=>{
  if(err) throw new Error(err);

  function readFiles(i){
    if(i >=files.length) return; // exit
    fs.readFile(path.join("ddd", files[i]), (err, content)=> {
      if(err) throw new Error(err);
      console.log(result.length)
      readFiles(i+1)
    })
  }

 readFiles(0)

})

Our pattern forces JS to read the files in order.

There are a number of ways to solve this aside doing the operations recursively. The problem with this approach is they are made one after the other which can be slow. There is a much more better approach below.

bashimport fs from "fs";
import path from "path";

fs.readdir("ddd", (err, files)=>{
  if(err) throw new Error(err);
  const results = [];
  let isRemaining = files.length;

  files.forEach((file, index)=> {
    --isRemaining
    fs.readFile(path.join("ddd",file), (err, readContent)=>{
      if(err) throw new Error(err);
      results[index] = readContent;

      if(!isRemaining) console.log(results.toString());
    })
  })
})

Callbacks are great but they have their limitations like the pyramid of doom ( also known as Callback Hell). In addition, Callback handlers weren't symbolic to async operations 2. In fact, it is confusing because non-blocking functions use them too. They can also have major concerns with coupling.

The community brought about Promises that can help handle these limitations better. Let's talk about it.

Promises

Instead of passing callback functions as argument to an async operation, a Promise is an object that allows us to handle (or better still watch for) success or failure of our async operations while separately chain multiple async calls to handle these events (instead of nesting with callbacks).

Let's promisify our previous callback. Promisifying is the transformation of callback based methods to promise.

bashimport { readFile } from 'fs';

let filename;

function promisify(fn){
  return function(file, cb = ()=>{}){
   return new Promise((resolve, reject)=>{
      fn(file, (err, data)=> {
        if(err) reject(err);
        else resolve(data)
      })
    })
  }
}

const promisifiedReadFile = promisify(readFile);
promisifiedReadFile('note.txt')
  .then(data => console.log(data.toString()))
  .catch(e => console.log(e))

The promisify function we used in the code above is in fact available for us as node util.

bashimport { readFile } from 'node:fs';
import { promisify } from 'node:util';

let filename;

const promisifiedReadFile = promisify(readFile);
promisifiedReadFile('note.txt')
  .then(data => console.log(data.toString()))
  .catch(e => console.log(e))

The Async keyword

Chaining promise handlers can be simpllified even more to feel like sync. There is the Async/Await keywords, they do these things:

  1. improve readability of async codes.
  2. simplifies variable scopes around async codes.
  3. improve error handling.
bashimport { readFile } from 'node:fs';
import { promisify } from 'node:util';

let filename;

const promisifiedReadFile = promisify(readFile);

try {
  const data = await promisifiedReadFile('note.txt');
  console.log(data.toString());
}catch(err){
  console.log(err)
}
The Event Loop

When dealing with async operations, it can sometimes be important to understand how multiple async operations and their handlers are managed or in what order they get back to the main thread. To answer these questions, we need to understand The call stack, event queues and the the event loop.

Listeners and Event Emitters

Another handler method that takes the game to a different level is the use of Event Listeners created with Emitter object.

An Emitter object has two main features:

  1. Emitting named events
  2. Registering ( and unregistering) listener functions.

To create an event emitter object, we can instantiate from the EventEmitter class or any class that extends it.

bashimport fs from 'node:fs';
import {EventEmitter} from 'node:events'

class ReaderEmitter extends EventEmitter {
  readFile(file){
    fs.readFile(file, (err, data)=> {
      if(err){
        this.emit('error', err);
        return
      }
      this.emit('data', data.toString());
    })
  }
}

const reader = new ReaderEmitter();

reader.on('data', data => { console.log(data) });
reader.on('error', err=> { throw new Error(err) });

reader.readFile('note.txt')

Questions to research on

  • How exactly does an handler function get executed in the main thread after its async operation is done outside the main execution context?
  • If JS runs on a single thread, what thread does an async operation run on?
  • When a function is called/completed, it reference gets popped out of the call stack. How does JavaScript knows if an async task is completed? What is used to identify its reference?

References

Footnotes

  1. Definition for Promises Pasted on Tue, Jul 29, 2025.
  2. A stackoverflow thread where devs are confused with the role of callback in sync ops Pasted on Sat, Aug 02, 2025.
  3. Why Promises over Callbacks Pasted on Tue, Jul 29, 2025.
  4. Pyramid of doom and troubles with additional indentation Pasted on Tue, Jul 29, 2025.
  5. Microtasks and queues Pasted on on, Aug 25, 2025

This page was published on 09/07/2025, last updated on 07/03/2026. Contributed to by kelvinsekx.