1const PENDING = 'PENDING';
2const FULFILLED = 'FULFILLED';
3const REJECTED = 'REJECTED';
4
5class MyPromise {
6 constructor(executor) {
7 this.state = PENDING;
8 this.value = undefined;
9 this.onFulfilledCallbacks = [];
10 this.onRejectedCallbacks = [];
11
12 const resolve = (val) => {
13 if (this.state === PENDING) {
14 this.state = FULFILLED;
15 this.value = val;
16 // Drain callbacks asynchronously in microtask
17 queueMicrotask(() => {
18 this.onFulfilledCallbacks.forEach(cb => cb(this.value));
19 });
20 }
21 };
22
23 const reject = (reason) => {
24 if (this.state === PENDING) {
25 this.state = REJECTED;
26 this.value = reason;
27 queueMicrotask(() => {
28 this.onRejectedCallbacks.forEach(cb => cb(this.value));
29 });
30 }
31 };
32
33 try {
34 executor(resolve, reject);
35 } catch (err) {
36 reject(err);
37 }
38 }
39
40 then(onFulfilled, onRejected) {
41 // Ensure handlers are functions; fallback to passthrough
42 const realOnFulfilled = typeof onFulfilled === 'function' ? onFulfilled : val => val;
43 const realOnRejected = typeof onRejected === 'function' ? onRejected : err => { throw err; };
44
45 // .then() MUST return a brand new Promise!
46 return new MyPromise((resolveNext, rejectNext) => {
47 const handleCallback = (callback) => {
48 try {
49 const result = callback(this.value);
50 // If returned value is itself a thenable/promise, resolve it
51 if (result instanceof MyPromise) {
52 result.then(resolveNext, rejectNext);
53 } else {
54 resolveNext(result);
55 }
56 } catch (error) {
57 rejectNext(error);
58 }
59 };
60
61 if (this.state === FULFILLED) {
62 queueMicrotask(() => handleCallback(realOnFulfilled));
63 } else if (this.state === REJECTED) {
64 queueMicrotask(() => handleCallback(realOnRejected));
65 } else {
66 // Still PENDING: enqueue handlers
67 this.onFulfilledCallbacks.push(() => handleCallback(realOnFulfilled));
68 this.onRejectedCallbacks.push(() => handleCallback(realOnRejected));
69 }
70 });
71 }
72
73 catch(onRejected) {
74 return this.then(null, onRejected);
75 }
76
77 static resolve(val) {
78 return new MyPromise((res) => res(val));
79 }
80
81 static reject(err) {
82 return new MyPromise((_, rej) => rej(err));
83 }
84}