Reputation: 1017
I never see a "microtask" queue referenced in online sources and I wondered if this is because the webapi queue is what the microtask is referring to?
Here's a YouTube video that was viewed 1.5. million times that explains the JS event loop, but the "microtask queue" isn't even referenced: https://www.youtube.com/watch?v=8aGhZQkoFbQ
ADDENDUM: This is a great resource to learn about tasks and microtask queues: https://developer.mozilla.org/en-US/docs/Web/API/HTML_DOM_API/Microtask_guide/In_depth This link doesn't answer my question, but it does touch on the topic and provides some helpful clarity.
Upvotes: 0
Views: 380
Reputation: 707976
Within the nodejs "event loop" are a number of different queues for things waiting to run. There's a queue for asynchronous I/O things like file operations. There's a separate step of the event loop for timers (not really a queue as timers are implemented within the event loop in a very specific way). There's a microtask queue for promises. As the event loop looks for the next thing to do, it has a specific order it looks for things and some things (such as resolved/rejected promises) have higher priority that other things waiting to run.
I never see a "microtask" queue referenced in online sources and I wondered if this is because the webapi queue is what the microtask is referring to?
In that specific video, "webapi" is used as a giant placeholder for all the things that browser adds to its Javascript environment that are not built into the Javascript language itself. This would include Ajax, DOM, etc... There are indeed multiple queues that are part of what the browser adds to the vanilla Javascript implementation.
The ECMAScript specification uses the terms Jobs and Job Queues. Microtask is often used in reference to promises and their implementation which you can see referenced here on MDN, but it's used to just try to explain how the specification or an implementation works - that term isn't actually in the specification.
In general, the term microtask is used to describe a subset of some larger task that is waiting to run. For example, if you had something like this (where $.get()
is an ajax call:
$.get("http://www.google.com").then(result => {
console.log("got the page");
}).catch(err => {
console.log(err);
});
Then, the browser would run $.get()
and, sometime later when it completes and the JS engine is free, a callback would get called that would resolve the promise that $.get()
returns. Resolving that promise would allow the promise to schedule it's .then()
handlers to run. They get scheduled by inserting them into the promise microtask queue. And, when the current bit of Javascript finishes and returns back to the event loop, the event loop will run the first thing in that microtask queue and it will run it before it runs most other things in other queues that are also serviced by the event loop.
Upvotes: 1