手写Promise

32 阅读1分钟
class MyPromise {
  constructor(executor) {
    this.state = "pending"; // 初始状态为pending
    this.value = undefined; // 用于存储成功的结果
    this.reason = undefined; // 用于存储失败的原因

    this.onFulfilledCallbacks = []; // 存储成功的回调函数
    this.onRejectedCallbacks = []; // 存储失败的回调函数
    //成功回调函数
    const resolve = (value) => {
      if (this.state == "pending") {
        this.state = "fulfilled";
        this.value = value;
        // 调用记录的回调函数
        this.onFulfilledCallbacks.forEach((fn) => {
          // console.log(fn.toString());
          fn(this.value);
        });
      }
    };
    //失败回调函数
    const reject = (reason) => {
      if (this.state == "pending") {
        this.state = "rejected";
        this.reason = reason;
        // 调用记录的回调函数
        this.onRejectedCallbacks.forEach((fn) => fn(this.reason));
      }
    };

    // 立即执行executor函数
    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  then(onFulfilled, onRejected) {
    return new MyPromise((resolve, reject) => {
      if (this.state === "fulfilled") {
        // 使用setTimeout模拟异步执行,确保回调函数是在当前执行栈清空后的下一个事件循环迭代中执行的
        setTimeout(() => {
          try {
            const x = onFulfilled(this.value);
            // 处理onFulfilled返回的Promise
            resolvePromise(resolve, reject, x);
          } catch (e) {
            reject(e);
          }
        }, 0);
      }
      if (this.state === "rejected") {
        setTimeout(() => {
          try {
            const x = onRejected(this.reason);
            resolvePromise(resolve, reject, x);
          } catch (e) {
            reject(e);
          }
        }, 0);
      }
      if (this.state === "pending") {
        // 如果Promise还在pending状态,需要将回调函数存储起来
        this.onFulfilledCallbacks.push(() => {
          setTimeout(() => {
            try {
              const x = onFulfilled(this.value);
              resolvePromise(resolve, reject, x);
            } catch (e) {
              reject(e);
            }
          }, 0);
        });
        this.onRejectedCallbacks.push(() => {
          setTimeout(() => {
            try {
              const x = onRejected(this.reason);
              this.handleResult(resolve, reject, x);
            } catch (e) {
              reject(e);
            }
          }, 0);
        });
      }
    });
  }
}

const resolvePromise = (resolve, reject, x) => {
  if (x instanceof MyPromise) {
    // 如果onFulfilled返回的是Promise,需要递归处理
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
};

// 使用示例
const p = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve("Hello, Promise!");
  }, 1000);
});

p.then((result) => {
  console.log(result); // 输出: Hello, Promise!
  return new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve("Another Promise!");
    }, 500);
  });
}).then((result) => {
  console.log(result); // 输出: Another Promise!
});