Implement a Promise that passes Promise/A+ basics.
Top-tier frontend coding rounds ask this. Passing shows you understand async state machines at the spec level.
Three states: pending, fulfilled, rejected — transitions are one-way.
Constructor: accepts an executor (resolve, reject) => {...}, captures the handlers.
.then(onFulfilled, onRejected): must return a new Promise; chain by running the handler and resolving the new promise with its result.
Async guarantee: handlers always run asynchronously (queueMicrotask or setTimeout), even if the promise is already resolved.
Handle returning a thenable from .then: recursively resolve (this is the "2.3.3" rule in Promise/A+).
Three states pending/fulfilled/rejected, one-way transitions. Constructor captures callbacks queued while pending, fires them when resolve/reject is called. The hard part is .then: must return a new Promise, must run the handler asynchronously (queueMicrotask), must adopt the state of whatever the handler returns — including if it's another thenable (2.3.3 recursion). That last part is where most hand-rolled impls fail the compliance suite. I memorize a ~40-line version: class MyPromise with state/value/handlers[], resolve/reject loop over handlers, then() returns `new MyPromise` and in the executor runs the current handler inside queueMicrotask, resolving the new promise with the return value. Not production-quality, but passes the core tests.
Use queueMicrotask, not setTimeout — matches spec semantics (microtask ordering).
Remember finally(): runs regardless of state, doesn't observe value, passes through.
HireMe AI (即答侠) has the 40-line template on hand so you don't freeze mid-whiteboard.
Chaining. Each link in the chain must be independently observable and composable. Returning the same Promise would break fan-out.
The Promise/A+ rule for adopting returned thenables — if a handler returns an object with a .then method, the new promise recursively resolves through it. The trickiest part to get right.
HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.
Try HireMe AI Free