The async programming model and especially how the event loop works.
The latter might be transparent to you 99.9% of the times, but then you’ll run into issues where your code behaves unexpectedly and you just need to execute it in the next tick (iteration of the event loop) instead.
and you just need to execute it in the next tick (iteration of the event loop) instead.
I consider myself pretty well versed in javascript however I can not imagine what you mean with this. How would "execute it in the next tick" look in code?
setImmediate sometimes, you run into a max callstack issue for function calls if you don't ensure that the next call comes on the next tick. This is especially important for recursive functions or looping functions that might call itself again.
Depends on how the code is structured. Sometimes a recursive function will call itself too many times and crash, unless you move the next call to the next tick. Logical exit conditions don't matter when you need the function to be called more times than is allowed by the max call limit in a single tick.
If I’m not mistaken, this act of exiting a recursive loop temporarily to resolve the call stack, and then resuming immediately, is referred to as a “thunk.”
Edit:
Also, for those who aren’t aware, I believe the max call stack size in Chrome is 10,000, but it’s different for each browser. So if you need to recursively iterate through something, you would ordinarily be limited to that number of iterations.
My favorite way to run code asynchronously as tightly as possible (absent node's nextTick stuff) is to use Promise.resolve().then(...).
That will schedule a microtask, which may end up running after other scheduled microtask, but still long before anything else. It's so fast it can often be "too fast", particularly if you're hoping the browser will redraw anything before calling your code again, the way a setTimeout(... ,0) would.
There are other approaches, like mildly abusing the postMessage API, but nothing as straightforward as an immediate promise.
105
u/ItalyPaleAle May 28 '19
The async programming model and especially how the event loop works.
The latter might be transparent to you 99.9% of the times, but then you’ll run into issues where your code behaves unexpectedly and you just need to execute it in the next tick (iteration of the event loop) instead.