# Microtasks and event loop Promise handlers `.then`/`.catch`/`.finally` are always asynchronous. Even when a Promise is immediately resolved, the code on the lines *below* your `.then`/`.catch`/`.finally` will still execute first. Here's the code that demonstrates it: ```js run 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 `.then` triggered after? What's going on? # Microtasks 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](https://tc39.github.io/ecma262/#sec-jobs-and-job-queues): - The queue is first-in-first-out: tasks enqueued first are run first. - Execution of a task is initiated only when nothing else is running. 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. ![](promiseQueue.png) 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 asynchronously. That is, it first gets queued, and executed when the current code is complete and previously queued handlers are finished. What if the order matters for us? How to make `code finished` work after `promise done`? Easy, just put it into the queue with `.then`: ```js run Promise.resolve() .then(() => alert("promise done!")) .then(() => alert("code finished")); ``` Now the order is as intended. ## Event loop Browser Javascript, as well as Node.js, is based on an *event loop*. "Event loop" is a process when the engine sleeps and waits for events, then reacts on those and sleeps again. Examples of events: - `mousemove`, a user moved their mouse. - `setTimeout` handler is to be called. - an external `