Administrator
发布于 2025-08-13 / 3 阅读
0
0

手写 Promise 极简版

/**
 * 
 * 规范
 * 1 Promise的状态只能从pending变为fulfilled或rejected,不能再变回pending。
 * 2 then方法可以被多次调用,且每次调用都返回一个新的Promise实例。
 * 3 then 接受两个函数作为参数,第一个函数在Promise成功时调用,第二个函数在Promise失败时调用。
 * 4 存在定时器的情况,需要定时器结束之后再执行then方法中的回调函数。
 * 
 */


class MyPromise {
  constructor(executor) {
    this.status = 'pending';
    this.promiseResult = undefined;
    this.reason = undefined;
    this.onFulfilledCallbacks = [];
    this.onRejectedCallbacks = [];

    const resolve = (promiseResult) => {
      if (this.status === 'pending') {
        this.status = 'fulfilled';
        this.promiseResult = promiseResult;
        this.onFulfilledCallbacks.forEach((callback) => callback(promiseResult));
      }
    };

    const reject = (reason) => {
      if (this.status === 'pending') {
        this.status = 'rejected';
        this.reason = reason;
        this.onRejectedCallbacks.forEach((callback) => callback(reason));
      }
    };

    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  then(onFulfilled, onRejected) {
    return new MyPromise((resolve, reject) => {
      const handleFulfilled = () => {
        try {
          const result = onFulfilled(this.promiseResult);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      };

      const handleRejected = () => {
        try {
          const result = onRejected(this.reason);
          resolve(result);
        } catch (error) {
          reject(error);
        }
      };

      if (this.status === 'fulfilled') {
        handleFulfilled();
      } else if (this.status === 'rejected') {
        handleRejected();
      } else {
        this.onFulfilledCallbacks.push(handleFulfilled);
        this.onRejectedCallbacks.push(handleRejected);
      }
    });
  }
}


评论