小白都懂的Promise!

88 阅读3分钟

好的,下面是一个简单的手写 Promise 实现,每行代码都附有注释,帮助小白理解。

// 定义一个 MyPromise 类
class MyPromise {
  // 构造函数,接收一个执行器函数 (executor) 作为参数
  constructor(executor) {
    // 初始化 Promise 的状态为 'pending'
    this.status = 'pending';
    // 初始化 Promise 的值,默认为 null
    this.value = null;
    // 初始化 Promise 的失败原因,默认为 null
    this.reason = null;
    // 用于存储成功回调函数的数组
    this.onFulfilledCallbacks = [];
    // 用于存储失败回调函数的数组
    this.onRejectedCallbacks = [];

    // 定义 resolve 函数,用于将 Promise 状态改为 'fulfilled'
    const resolve = (value) => {
      // 只有在状态为 'pending' 时才能改变状态
      if (this.status === 'pending') {
        // 将状态改为 'fulfilled'
        this.status = 'fulfilled';
        // 保存成功时的值
        this.value = value;
        // 执行所有成功回调函数
        this.onFulfilledCallbacks.forEach(callback => callback());
      }
    };

    // 定义 reject 函数,用于将 Promise 状态改为 'rejected'
    const reject = (reason) => {
      // 只有在状态为 'pending' 时才能改变状态
      if (this.status === 'pending') {
        // 将状态改为 'rejected'
        this.status = 'rejected';
        // 保存失败时的原因
        this.reason = reason;
        // 执行所有失败回调函数
        this.onRejectedCallbacks.forEach(callback => callback());
      }
    };

    // 执行 executor 函数,并传入 resolve 和 reject 作为参数
    try {
      executor(resolve, reject);
    } catch (error) {
      // 如果 executor 执行出错,直接 reject
      reject(error);
    }
  }

  // 定义 then 方法,接收两个回调函数:onFulfilled 和 onRejected
  then(onFulfilled, onRejected) {
    // 返回一个新的 Promise,支持链式调用
    return new MyPromise((resolve, reject) => {
      // 如果状态是 'fulfilled',直接执行 onFulfilled
      if (this.status === 'fulfilled') {
        // 使用 setTimeout 模拟异步执行
        setTimeout(() => {
          try {
            // 执行 onFulfilled 并获取返回值
            const result = onFulfilled(this.value);
            // 如果返回值是一个 Promise,则等待它完成
            if (result instanceof MyPromise) {
              result.then(resolve, reject);
            } else {
              // 否则直接 resolve 返回值
              resolve(result);
            }
          } catch (error) {
            // 如果 onFulfilled 执行出错,reject 错误
            reject(error);
          }
        }, 0);
      }

      // 如果状态是 'rejected',直接执行 onRejected
      if (this.status === 'rejected') {
        // 使用 setTimeout 模拟异步执行
        setTimeout(() => {
          try {
            // 执行 onRejected 并获取返回值
            const result = onRejected(this.reason);
            // 如果返回值是一个 Promise,则等待它完成
            if (result instanceof MyPromise) {
              result.then(resolve, reject);
            } else {
              // 否则直接 resolve 返回值
              resolve(result);
            }
          } catch (error) {
            // 如果 onRejected 执行出错,reject 错误
            reject(error);
          }
        }, 0);
      }

      // 如果状态是 'pending',将回调函数存入数组,等待状态改变后执行
      if (this.status === 'pending') {
        this.onFulfilledCallbacks.push(() => {
          // 使用 setTimeout 模拟异步执行
          setTimeout(() => {
            try {
              // 执行 onFulfilled 并获取返回值
              const result = onFulfilled(this.value);
              // 如果返回值是一个 Promise,则等待它完成
              if (result instanceof MyPromise) {
                result.then(resolve, reject);
              } else {
                // 否则直接 resolve 返回值
                resolve(result);
              }
            } catch (error) {
              // 如果 onFulfilled 执行出错,reject 错误
              reject(error);
            }
          }, 0);
        });

        this.onRejectedCallbacks.push(() => {
          // 使用 setTimeout 模拟异步执行
          setTimeout(() => {
            try {
              // 执行 onRejected 并获取返回值
              const result = onRejected(this.reason);
              // 如果返回值是一个 Promise,则等待它完成
              if (result instanceof MyPromise) {
                result.then(resolve, reject);
              } else {
                // 否则直接 resolve 返回值
                resolve(result);
              }
            } catch (error) {
              // 如果 onRejected 执行出错,reject 错误
              reject(error);
            }
          }, 0);
        });
      }
    });
  }
}

// 示例用法
const promise = new MyPromise((resolve, reject) => {
  setTimeout(() => {
    resolve('成功啦!');
  }, 1000);
});

promise.then(
  (value) => {
    console.log(value); // 1秒后输出: 成功啦!
    return '继续成功!';
  },
  (reason) => {
    console.log(reason);
  }
).then((value) => {
  console.log(value); // 输出: 继续成功!
});

代码解释:

  1. MyPromise:这是我们的自定义 Promise 类。
  2. constructor:构造函数,接收一个 executor 函数,并初始化状态、值、原因以及回调函数数组。
  3. resolvereject:这两个函数用于改变 Promise 的状态,并执行相应的回调函数。
  4. then 方法:用于注册 onFulfilledonRejected 回调函数,并返回一个新的 Promise,支持链式调用。
  5. setTimeout:用于模拟 Promise 的异步行为。

总结:

这个简单的 Promise 实现涵盖了 Promise 的基本功能,包括状态管理、异步执行、链式调用等。希望这个代码和注释能帮助你理解 Promise 的工作原理!