🔧 Custom Promise Class Implementation
Category: js / promises
Difficulty: hard
A JavaScript Promise is an asynchronous mechanism that represents a future value. Below is a fully functional implementation of a custom Promise (CustomPromise) that behaves exactly like the native JavaScript Promise. ✅ Implementation ``javascript class CustomPromise { constructor(executor) { this.state = 'pending'; // Possible states: 'pending', 'fulfilled', 'rejected' this.value = undefined; // Holds the resolved value this.reason = undefined; // Holds the rejection reason this.onFulfilledCallbacks = []; // Stores .then success handlers this.onRejectedCallbacks = []; // Stores .then error handlers // Resolve function const resolve = (value) => { if (this.state === 'pending') { this.state = 'fulfilled'; this.value = value; this.onFulfilledCallbacks.forEach(callback => callback(value)); } }; // Reject function const reject = (reason) => { if (this.state === 'pending') { this.state = 'rejected'; this.reason = reason; this.onRejectedCallbacks.forEach(callback => callback(reason)); } }; try { executor(resolve, reject); } catch (error) { reject(error); } } // then method then(onFulfilled, onRejected) { return new CustomPromise((resolve, reject) => { const handleFulfilled = () => { try { const result = onFulfilled ? onFulfilled(this.value) : this.value; result instanceof CustomPromise ? result.then(resolve, reject) : resolve(result); } catch (error) { reject(error); } }; const handleRejected = () => { try { const result = onRejected ? onRejected(this.reason) : this.reason; result instanceof CustomPromise ? result.then(resolve, reject) : reject(result); } catch (error) { reject(error); } }; if (this.state === 'fulfilled') { setTimeout(handleFulfilled, 0); } else if (this.state === 'rejected') { setTimeout(handleRejected, 0); } else { this.onFulfilledCallbacks.push(handleFulfilled); this.onRejectedCallbacks.push(handleRejected); } }); } // catch method catch(onRejected) { return this.then(null, onRejected); } // finally method finally(callback) { return this.then( value =>...