4 ms·
Case in point which tripped me up recently. Knowing that promise.then() callbacks aren't called synchronously[1], even if the promise is already resolved, I ass
by _greim_ 11y ago
Case in point which tripped me up recently. Knowing that promise.then() callbacks aren't called synchronously[1], even if the promise is already resolved, I assumed that this:
var tick = Promise.resolve();
async function cpuBoundJob() {
for (...many iterations...) {
// crunch some bits
await tick;
}
}
...would spread out a heavy calculation and allow other things to break in occasionally and do work. But based on tests, nothing ever got a chance to run until the whole job finished.
My current understanding (correct me if I'm wrong) is that promise.then() calls you back from a microtask, which means "await tick" doesn't teleport you into the next tick, just out of the current call stack into a new one at the end of the same tick, regardless of how many things are piled up waiting on the next tick. In other words the entire calculation remains one big CPU-blocking chunk. This modified version ended up working as expected, since setImmediate is (apparently) not a microtask.
var tick = () => new Promise(res => setImmediate(res))
async function cpuBoundJob() {
for (...many iterations...) {
// crunch some bits
await tick();
}
}
[1] https://promisesaplus.com/#point-34 https://promisesaplus.com/#point-34