Create Your Own Promise

Hard
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Create Your Own Promise

Approach

Implement a simplified Promise class with pending/fulfilled/rejected states and a handlers queue. The constructor runs the executor synchronously, calling resolve or reject to transition state. The then method returns a new MyPromise, queuing handlers if still pending or scheduling them asynchronously if already settled.

Complexity Analysis

Time
O(n) where n is the handler chain length
Space
O(n)

Pattern

Promise Implementation

Why It Works

State machine semantics ensure a promise transitions only once, and deferred handler execution via the queue guarantees then callbacks registered before settlement are invoked when the value becomes available.

Updated Feb 2026