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); }); }
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); }); }
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:
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!