Home > Web Front-end > JS Tutorial > How Can I Correctly Implement Non-Blocking Functions in Node.js?

How Can I Correctly Implement Non-Blocking Functions in Node.js?

Patricia Arquette
Release: 2024-12-09 10:10:09
Original
357 people have browsed it

How Can I Correctly Implement Non-Blocking Functions in Node.js?

Correct Implementation of Non-Blocking Functions in Node.js

Despite the misconception, merely wrapping code in a Promise does not render it non-blocking. The Promise executor function, being synchronous in nature, blocks execution. This is the reason for the delay observed in the provided code before printing subsequent lines.

The Problem with the Provided Code

The code initially appears to be non-blocking, utilizing a Promise to return the result of the computationally intensive longRunningFunc. However, upon execution, we observe a delay before the second and third lines are printed, indicating that the program is waiting for the Promise to resolve.

True Non-Blocking Code in Node.js

To create genuinely non-blocking code in Node.js, we have several options:

  • Child Processes: Execute the code in a separate child process, receiving an asynchronous notification upon completion.
  • Worker Threads (Node.js v11 ): Leverage the experimental Worker Threads introduced in Node.js v11.
  • Native Code Add-ons: Develop custom native add-ons utilizing libuv or OS-level threads.
  • Leveraging Existing Asynchronous APIs: Build upon existing asynchronous APIs, avoiding prolonged code execution in the main thread.

Revising the Example

While wrapping the code in a Promise is not sufficient for non-blocking behavior, we can use setTimeout() to schedule the for-loop for later execution:

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 approach shifts the timing of the for-loop, giving the appearance of non-blocking behavior. However, it is important to note that the for-loop still executes synchronously once scheduled. To achieve true non-blocking code, we would need to employ one of the techniques described earlier.

The above is the detailed content of How Can I Correctly Implement 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