I need to do some CPU heavy computation in node on socket server, but I don't want to block my IO.
Is it possible to use ES6 / ES7 features to achieve this in nice way.
My first attempt was to use async and await, but seems like, if heavy synchronous functions are called before timer events, timer events gets called only after all heavy computation calls are executed. https://jsfiddle.net/bz31vk97/1/
let t = 0
setInterval(async function() {
t = t + 1
console.log("timer: ", t)
}, 1000)
async function syncDelay(ms) {
console.log("syncDelay: ", ms, "ms")
let t1 = Date.now()
while (Date.now() - t1 < ms) {}
return ms
}
async function heavyWork() {
for (let i = 0; i < 10; i++) {
await syncDelay(500)
}
}
heavyWork()
console.log("after calling heavyWork")
Same when I replace await call with setImmediate on node:
setImmediate(() => syncDelay(500))
Both versions first calls all syncDelays and only then starts to call timer events.
Is there any way to allow IO and timer events to be called between several cpu heavy calls?