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