Questions about the order of execution of this code snippet : <p>So I been reading a tutorial about Javascript promises these days.</p>

<p>here is an example from it used to explain the macrotask queue(i.e. the event loop) and the microtask queue.</p>

<pre><code>let promise = Promise.reject(new Error("Promise Failed!"));
promise.catch(err =&gt; alert('caught'));

// no error, all quiet
window.addEventListener('unhandledrejection', event =&gt; alert(event.reason));
</code></pre>

<p>It says that because <code>promise.catch</code> catches the error so the last line, the event handler never gets to run. I can understand this. But then he tweaked this example a little bit.</p>

<pre><code>let promise = Promise.reject(new Error("Promise Failed!"));
setTimeout(() =&gt; promise.catch(err =&gt; alert('caught')));

// Error: Promise Failed!
window.addEventListener('unhandledrejection', event =&gt; alert(event.reason));
</code></pre>

<p>This time he says the event handler is gonna run first and catch the error and <strong>after</strong> this the <code>promise.catch</code> catches the error eventually.</p>

<p>What I do not understand about the second example is, why did the event handler run before the <code>promise.catch</code>? </p>

<p>My understanding is,</p>

<ol>
<li>Line one, we first encounter a promise, and we put it on the microtask queue.</li>
<li>Line two, we have a <code>setTimeout</code>, we put it on the macrotask queue,</li>
<li>Line three, we have an event handler, and we put the handler on the macrotask queue waiting to be fired</li>
</ol>

<p>Then, because microtask has higher priority than macrotask. We run the promise first. After it, we dequeue the first task on macrotask queue, which is the <code>setTimeout</code>. So from my understanding, the error should be caught by the function inside <code>setTimeout</code>.</p>

<p>Please correct me.</p>
