notes · learnings ·
Who handles asynchronous work?
A question about waiting for asynchronous work led to Workers and response order. Separating the causes of a frozen UI helped me see how to address it.
While studying the event loop, my first question was who handles asynchronous work. If JavaScript follows one execution flow at a time, how can other code run while it waits for a network response?
The browser handles the wait, while the JavaScript that deals with the result waits for its turn to run later. This also helped me distinguish Promises from microtasks. A Promise is an object representing a result, while a microtask is a way that code reacting to that result gets executed. The word “asynchronous” had been bundling together the result, the wait, and the execution that follows.
Then why does a long calculation freeze the screen even with async? Waiting for a response and computing on the CPU are different kinds of work. await does not move a calculation to another thread. Moving it to a Worker can let the screen respond to input even if the calculation takes just as long. Finishing quickly and remaining usable while waiting are different goals too.
Another question followed. Does a single execution flow eliminate ordering problems? Responses can arrive in a different order from their requests. Preventing an old search result from overwriting the latest screen requires a decision about which response to apply. Now, when a screen freezes or results appear out of order, I want to first distinguish waiting, calculation, and applying the result.
Lecture: What the heck is the event loop anyway?, Philip Roberts