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
saved by
related reading
- javascript - Difference between microtask and macrotask within an event loop context - Stack Overflowstackoverflow.com
- JavaScript Loading Priorities in Chromeaddyosmani.com
- Reading 15: Promisesweb.mit.edu
- What the heck is the event loop anyway? | Philip Roberts | JSConf EUyoutube.com
- The Event Loop and Callback Hell - Wes Boswesbos.com
- Promise - JavaScript | MDNdeveloper.mozilla.org
- TypeScript Structured Concurrencythecandidstartup.org
- Notes on structured concurrency, or: Go statement considered harmful - njs blogvorpus.org
- (Quite) A Few Words About Asyncyoric.github.io
- What Async Promised and What it Delivered — Causalitycausality.blog
- JavaScript Async Promisesw3schools.com
- 'return await promise' vs 'return promise' in JavaScriptdmitripavlutin.com