I got this piece of code :
import http from 'http';
function compute() {
let [sum, i] = [1, 1];
while (i<1000000000) {
5*2
i++;
}
console.log("good");
process.nextTick(compute);
}
http.createServer((request, response) => {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World');
}).listen(5000, '127.0.0.1');
http.request({hostname: '127.0.0.1', port: 5000}, (response) => {
console.log("here !");
}).end();
compute();
the output for that is always : "good, "good" ... and the HTTP request didn't get called. I thought that process.nextTick should solve that problem, but server is still blocked. Why ? How can I fix it ?
Instead of process.nextTick
rather use set setImmediate
. Callbacks passed to nextTick
are processed before IO callbacks whereas callbacks passed to setImmediate
are processed after any that are already pending.
Replace process.nextTick(compute);
with setImmediate(compute);
.
Moving the CPU work to a child process or worker is also possible. But I won't describe that as my main point was to explain how:
function compute() {
...
console.log("good");
process.nextTick(compute);
}
would block the HTTP server from handling requests ignoring the while
loop which has its own problem.
See setImmediate vs. nextTick for more.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments