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; iWhile 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; iThis 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:
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