3 ms·
Another important concept for JS devs to understand is (macro)tasks and microtasks. This is becoming especially important in ES6 and beyond (due to Promises lev
by nevir 11y ago
Another important concept for JS devs to understand is (macro)tasks and microtasks. This is becoming especially important in ES6 and beyond (due to Promises leveraging microtasks).
http://stackoverflow.com/questions/25915634/difference-between-microtask-and-macrotask-within-an-event-loop-context http://stackoverflow.com/questions/25915634/difference-betwe... has a decent overview
- _greim_ 11y agoCase 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