"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Write Truly Non-Blocking Functions in Node.js?

How to Write Truly Non-Blocking Functions in Node.js?

Posted on 2025-03-10
Browse:583

How to Write Truly Non-Blocking Functions in Node.js?

Correct Way to Write a Non-Blocking Function in Node.js

The non-blocking paradigm is crucial in Node.js for achieving high performance. However, it can be challenging to write truly non-blocking functions that do not impede the event loop's progress.

Understanding Non-Blocking Behavior

Wrapping code in a Promise does not inherently make it non-blocking. The Promise executor function is executed synchronously, meaning that long-running code within it will block the execution of other operations.

Example: Promise-Wrapped Blocking Function

Consider the following function:

function longRunningFunc(val, mod) {
    return new Promise((resolve, reject) => {
        let sum = 0;
        for (let i = 0; i 

While this function returns a Promise, the code within the executor is blocking. The event loop will wait until this code completes before executing other operations.

Simulating Asynchronicity with setTimeout

One approach to emulate non-blocking behavior in this case is to use setTimeout:

function longRunningFunc(val, mod) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            let sum = 0;
            for (let i = 0; i 

This code schedules the long-running loop to execute after a 10-millisecond delay. However, it's still blocking within that delayed execution period.

True Non-Blocking Approaches

To create truly non-blocking functions, you need to use techniques that move code execution outside the main Node.js thread:

  • Child Processes: Create a separate process to handle long-running tasks.
  • Worker Threads: Utilize the experimental Worker Threads feature in Node.js to create multiple threads within a single process.
  • Native Code: Write C or other native code extensions that use asynchronous system calls or threads.
  • Existing Asynchronous APIs: Leverage asynchronous operations provided by Node.js core modules, such as file I/O with fs.readFile, HTTP requests with http.get, or database queries with mongoose.connect.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3