Question 27

Question

How would you implement a custom promise that tracks the number of fulfilled/rejected promises created?

Answer

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

Explanation:

  • fulfilledCount and rejectedCount: These properties track the number of times the Promise has been successfully fulfilled or rejected, respectively.

  • _resolve and _reject: Private methods to handle fulfillment and rejection internally.

  • then Method: Allows you to register callbacks for fulfillment (onFulfilled) and rejection (onRejected).

  • Public Methods resolve and reject: Provide a way to externally resolve or reject the Promise.

Last updated