Reputation: 1
I have this code:
import http from 'http';
const longComputation = () => {
return new Promise((resovle) => {
console.log('started');
let sum = 0;
for (let j = 0; j < 10; j++) {
for (let i = 0; i < 1e9; i++) {
sum += i;
}
}
resovle(sum);
});
};
const server = http.createServer();
server.on('request', async (req, res) => {
console.log('request');
if (req.url === '/compute') {
const sum = await longComputation();
console.log('finished');
return res.end(`Sum is ${sum}`);
} else {
res.end('Ok');
}
});
server.listen(3000);
The purpose of longComputation
is to simulate long running task,
then I make two requests:
but when I make the second request the server not respond until the first one is finish,
**This is the output of the two request - you can see the second request print last until the first proccessed.
why is that happanning?
Upvotes: 0
Views: 46
Reputation: 21364
This is because JavaScript is single-threaded. You will want to read a little about cooperative multi-tasking, which is the multi-tasking model used by JS. Nothing ever happens in parallel in JS unless you use worker thread explicitly (and these are still somewhat new). So your long computation will stall everything in your app, including the server that you want to respond to the second request.
If you really need long-running computations I would either use a worker thread, or, in many cases, think about implementing the computation in a C++ library (which will also be faster). Alternatively you can break down the computation into many logical chunks, and relinquish control between chunks. One way to accomplish that is to use setTimeout(() => processChunk(nextChunk), 1)
to start the next chunk.
Upvotes: 1