Microtasks and event loop
Even when a Promise is immediately resolved, the code on the lines below .then/.catch/.finally will still execute before these handlers . Here’s the demo: If you run it, you see code finished first, and then promise done. That’s strange, because the promise is definitely done from the beginning. Why did the .then trigger afterwards? What’s going on? Asynchronous tasks need proper management. For that, the standard specifies an internal queue PromiseJobs, more often referred to as “microtask queue” (v8 term). As said in the specification: Or, to say that simply, when a promise is ready, its .then/catch/finally handlers are put into the queue. They are not executed yet. JavaScript engine takes a task from the queue and executes it, when it becomes free from the current code. That’s why “code finished” in the example above shows first. Promise handlers always go through that internal queue. If there’s a chain with multiple .then/catch/finally, then every one of them is executed asynchrono
Promise handlers .then / .catch / .finally are always asynchronous. Even when a Promise is immediately resolved, the code on the lines below .then / .catch / .finally will still execute before these handlers . Here’s the demo: let promise = Promise.resolve(); promise.then(() => alert("promise done")); alert("code finished"); // this alert shows first If you run it, you see code finished first, and then promise done . That’s strange, because the promise is definitely done from the beginning. Why did the .then trigger afterwards? What’s going on? Microtasks Asynchronous tasks need proper managem
Explore this link on the map →saved by
related reading
- javascript - Difference between microtask and macrotask within an event loop context - Stack Overflowstackoverflow.com
- Reading 15: Promisesweb.mit.edu
- Promise - JavaScript | MDNdeveloper.mozilla.org
- The Event Loop and Callback Hell - Wes Boswesbos.com
- JavaScript Async Promisesw3schools.com
- TypeScript Structured Concurrencythecandidstartup.org
- What Async Promised and What it Delivered — Causalitycausality.blog
- Reading 16: Mutual Exclusionweb.mit.edu
- python - How does asyncio actually work? - Stack Overflowstackoverflow.com
- Futures and promises - Wikipediaen.wikipedia.org
- JavaScript execution model - JavaScript | MDNdeveloper.mozilla.org
- Reading 17: Callbacks and Graphical User Interfacesweb.mit.edu