I have a CPU-heavy calculation function in my Node.js backend, and I expected it to run asynchronously because I wrapped it inside a Promise. However, when I call this function, the entire server becomes unresponsive for a moment. Other incoming requests slow down, and some are delayed until the calculation completes.
Here is a simplified example
function heavyTask() {
// Simulating CPU-heavy work
let count = 0;
for (let i = 0; i < 1e9; i++) {
count += i;
}
return count;
}
function runTaskAsync() {
return new Promise((resolve) => {
const result = heavyTask(); // expected this to be async
resolve(result);
});
}
app.get("/calculate", async (req, res) => {
const result = await runTaskAsync();
res.send({ result });
});
Even though runTaskAsync() returns a Promise, the CPU-intensive loop still blocks the event loop, and the server cannot handle other requests smoothly. I thought Promises made code asynchronous, so I’m confused about why this still blocks everything.
My questions
Why does the event loop still get blocked even though I used a Promise?
What is the correct way to run CPU-heavy work without blocking the main thread?
Should I use Worker Threads, Child Processes, or something else?
Environment
Node.js v18
Express.js server
What is the proper approach to fix this?