Sub topic 8
Promises Run as Microtasks
This chapter assumes you can write promise chains with then and catch, and that you have read the previous chapter on the microtask queue. That chapter showed that the microtask queue is drained completely after each task. This chapter covers which promise operations add jobs to that queue, at what moment they are added, and how many microtask "ticks" each step of a chain takes.
The Executor Runs Synchronously
The function you pass to new Promise(...) is called the executor. It runs immediately and synchronously, on the current call stack. Only the reactions, meaning the callbacks passed to then, catch, and finally, are deferred.
console.log('start');
new Promise((resolve) => {
console.log('executor');
resolve('value');
console.log('after resolve');
}).then((v) => console.log('then', v));
console.log('end');
// Output: start, executor, after resolve, end, then valueCalling resolve does not stop the executor and does not run the handler. It changes the promise's state to fulfilled and, if handlers are waiting, queues a job for each of them. The code after resolve keeps running.
When a Reaction Job Gets Queued
The ECMAScript specification calls each deferred promise callback a PromiseReactionJob. A reaction job can be queued at two points:
thenis called on a promise that has already settled. The job is queued right away.- A pending promise settles. Every reaction registered so far is queued, in the order it was registered.
A pending promise never runs anything when you call then on it. It records the reaction in an internal list and waits.
The second point explains why a promise that settles inside a timer callback runs its handlers before the next timer:
const p = new Promise((resolve) => {
setTimeout(() => {
resolve('done');
console.log('timer callback ends');
}, 0);
});
p.then((v) => console.log(v));
setTimeout(() => console.log('second timer'), 0);
// Output: timer callback ends, done, second timerThe first timer task calls resolve, which queues the then handler as a microtask. When that task finishes, the microtask queue is drained, so done is logged before the event loop picks up the second timer task.
Each `then` Returns a New Promise
then always returns a new promise, which this chapter calls the derived promise. That promise is settled by whatever happens inside the handler:
| Inside the handler | The derived promise |
|---|---|
| Returns a plain value `v` | Fulfills with `v` |
| Throws an error `e` | Rejects with `e` |
| Returns a promise or other thenable | Adopts its eventual state (costs extra ticks, see below) |
| Handler missing for this outcome | Passes the value or reason through unchanged |
The derived promise settles only when the handler runs. So the next then in a chain cannot be queued until the previous handler has finished. Each link in a chain therefore takes at least one separate microtask.
Chains Interleave
Because each link queues the next one only when it runs, two independent chains take turns:
Promise.resolve()
.then(() => console.log('a1'))
.then(() => console.log('a2'));
Promise.resolve()
.then(() => console.log('b1'))
.then(() => console.log('b2'));
// Output: a1, b1, a2, b2Here is the queue at each step:
- Synchronous code: both
Promise.resolve()values are already fulfilled, soa1andb1are queued. The queue is[a1, b1]. Thea2andb2handlers are stored on pending derived promises. a1runs and fulfills its derived promise, which queuesa2. The queue is[b1, a2].b1runs and queuesb2. The queue is[a2, b2].a2runs, thenb2runs.
A common mistake is to assume a whole chain runs "at once" once it starts. It runs one link per microtask, and other jobs can run between links.
Rejections Also Move One Link per Tick
catch(fn) is shorthand for then(undefined, fn). When a rejection reaches a then that has no rejection handler, the default "pass-through" reaction still runs as a job. Skipped links cost ticks too.
Promise.reject(new Error('x'))
.then(() => console.log('skipped'))
.catch(() => console.log('caught'));
Promise.resolve()
.then(() => console.log('1'))
.then(() => console.log('2'))
.then(() => console. Output: 1, caught, 2, 3The pass-through job for the first then runs first and rejects its derived promise. That queues the catch handler behind 1. A deeper chain of skipped then calls pushes the catch handfn) behaves similarly. Its callback runs as a reaction job, and it then passes the original value or reason through. Internally it does this by waiting on a promise, so finally adds more ticks than a plain then`.
Resolving With a Promise Costs Extra Ticks
When you resolve a promise with a value that is itself a thenable (an object with a then method), the engine cannot copy the state directly. It queues a PromiseResolveThenableJob, and that job calls the thenable's then. That then call queues another reaction job. Adopting a promise this way takes two extra microtasks.
const p = Promise.resolve();
new Promise((resolve) => resolve(p))
.then(() => console.log('resolved with promise'));
p.then(() => console.log('t1'))
.then(() => console.log('t2'))
.then(() => console.log('t3'));
// Output: t1, t2, resolved with promise, t3The queue evolves like this:
resolve(p)queues the thenable jobJ. Thenp.then(t1)queuest1. The queue is[J, t1].Jcallsp.then(...).pis already fulfilled, so a resolving jobRis queued. The queue is[t1, R].t1runs and queuest2. The queue is[R, t2].Rfulfills the outer promise, which queues its handlerH. The queue is[t2, H].t2runs and queuest3, thenHlogs, thent3logs.
The same cost applies when a then handler returns a promise. Returning somePromise from a handler delays the next link by two extra ticks compared with returning a plain value.
Summary of Tick Costs
| Operation | Microtasks before the next handler can run |
|---|---|
| `then` on an already-settled promise | 1 |
| Each further link in a chain | 1 per link, including skipped links |
| Handler returns a plain value | 1 for the next link |
| Handler returns a promise, or `resolve(promise)` | 3 (1 + 2 for thenable adoption) |
| `Promise.resolve(nativePromise)` | 0 extra (same object returned) |
Unhandled Rejections and Timing
A rejected promise with no rejection handler is reported as unhandled. Hosts check for this after the microtask queue is drained. In browsers this fires the unhandledrejection event, and Node.js prints a warning or, by default since Node.js 15, exits the process. If you attach a handler later in the same microtask checkpoint, nothing is reported. If you attach it in a later task, such as inside a setTimeout, the rejection has already been reported. Browsers then fire rejectionhandled. Attach catch handlers in the same synchronous block that creates the promise.
Common Errors
- Expecting
resolve()to run handlers immediately. It only queues them. - Assuming a chain runs without interruption. Other microtasks can run between links.
- Forgetting that returning a promise from a handler adds ticks. This changes ordering relative to parallel chains.
- Treating the executor as asynchronous. Heavy work inside
new Promise(...)blocks the thread just like any other synchronous code.
The next chapter shows how async functions and await are built from these same reaction jobs.
Exercise
What does this code print, and why? Promise.resolve().then(() => console.log('x1')).then(() => console.log('x2')); new Promise((r) => { console.log('exec'); r(); }).then(() => console.log('y1')); console.log('sync');
Show answer
exec, sync, x1, y1, x2. The executor runs synchronously, so 'exec' prints before 'sync'. Both promises are fulfilled during synchronous code, so x1 and y1 are queued in that order. x1 queues x2 when it runs, which puts x2 behind y1.
Exercise
A handler returns Promise.resolve(42) instead of 42. A parallel chain logs 'p1', 'p2', 'p3', 'p4' in consecutive links, started at the same time. Where does the next link after the 42-returning handler run, relative to the p-chain? Assume the 42-returning handler is the first link of its chain and is queued before p1.
Show answer
The 42-returning handler runs first, then p1. Returning a promise costs two extra ticks (thenable job, then resolving job), so the next link runs after p3 and before p4. The order is: handler, p1, p2, p3, next link, p4. If the handler returned a plain 42, the next link would run after p1, before p2.
Exercise
Why does attaching .catch inside a setTimeout(fn, 0) after creating a rejected promise still trigger an unhandled rejection report?
Show answer
Hosts check for unhandled rejections after the microtask queue is drained at the end of the current task. The setTimeout callback runs in a later task, so by the time catch is attached, the rejection has already been reported as unhandled.