How would you implement a custom promise that tracks the number of fulfilled/rejected promises created?
class CustomPromise {
constructor() {
this.fulfilledCount = 0;
this.rejectedCount = 0;
this.state = 'pending'; // Initial state
this._resolve = (value) => {
if (this.state !== 'pending') return;
this.state = 'fulfilled';
this.fulfilledCount++;
// Resolve callback if it exists
if (this._onFulfilled) {
this._onFulfilled(value);
}
};
this._reject = (reason) => {
if (this.state !== 'pending') return;
this.state = 'rejected';
this.rejectedCount++;
// Reject callback if it exists
if (this._onRejected) {
this._onRejected(reason);
}
};
}
then(onFulfilled, onRejected) {
this._onFulfilled = onFulfilled;
this._onRejected = onRejected;
return this; // Allow chaining
}
// Example: Public method to handle resolve/reject
resolve(value) {
this._resolve(value);
}
reject(reason) {
this._reject(reason);
}
get fulfillmentCount() {
return this.fulfilledCount;
}
get rejectionCount() {
return this.rejectedCount;
}
}
// Example Usage:
const promise1 = new CustomPromise();
promise1
.then((value) => console.log('Fulfilled:', value))
.catch((error) => console.error('Rejected:', error));
promise1.resolve(42); // Logs 'Fulfilled: 42'
console.log("Fulfillment Count:", promise1.fulfillmentCount); // Output: 1