flâneur — a map of the web's best reading

Microtasks and event loop

tr.javascript.info · 1,028 words · saved by 3 readers

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