Home > Web Front-end > JS Tutorial > How to Write Truly Non-Blocking Functions in Node.js?

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

Mary-Kate Olsen
Release: 2024-12-04 19:11:13
Original
249 people have browsed it

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 < 100000; i++) {
            for (let j = 0; j < val; j++) {
                sum += i + j % mod;
            }
        }
        resolve(sum);
    });
}
Copy after login

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 < 100000; i++) {
                for (let j = 0; j < val; j++) {
                    sum += i + j % mod;
                }
            }
            resolve(sum);
        }, 10);
    });
}
Copy after login

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.

The above is the detailed content of How to Write Truly Non-Blocking Functions in Node.js?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template