手写Promise

class Promise {
  constructor(executor) {
    // 初始化 Promise 状态和值
    this.state = 'pending';
    this.value = undefined;
    this.reason = undefined;

    // 初始化 Promise 的回调函数数组
    this.onResolvedCallbacks = [];
    this.onRejectedCallbacks = [];

    // 定义 resolve 和 reject 函数
    const resolve = value => {
      if (this.state === 'pending') {
        // 修改 Promise 的状态和值
        this.state = 'fulfilled';
        this.value = value;

        // 执行 Promise 的 onResolvedCallbacks 数组中的回调函数
        this.onResolvedCallbacks.forEach(cb => cb());
      }
    };

    const reject = reason => {
      if (this.state === 'pending') {
        // 修改 Promise 的状态和值
        this.state = 'rejected';
        this.reason = reason;

        // 执行 Promise 的 onRejectedCallbacks 数组中的回调函数
        this.onRejectedCallbacks.forEach(cb => cb());
      }
    };

    // 执行 executor 函数,并在执行过程中调用 resolve 和 reject 函数
    try {
      executor(resolve, reject);
    } catch (err) {
      reject(err);
    }
  }

  then(onFulfilled, onRejected) {
    // 如果 onFulfilled 和 onRejected 不是函数,则忽略它们
    onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
    onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };

    // 创建一个新的 Promise 对象
    const promise2 = new Promise((resolve, reject) => {
      // 当前 Promise 的状态为 fulfilled 时,异步执行 onFulfilled 函数
      if (this.state === 'fulfilled') {
        setTimeout(() => {
          try {
            // 获取 onFulfilled 函数的返回值 x,并将其传递给 resolvePromise 处理
            const x = onFulfilled(this.value);
            resolvePromise(promise2, x, resolve, reject);
          } catch (err) {
            reject(err);
          }
        });
      }
      // 当前 Promise 的状态为 rejected 时,异步执行 onRejected 函数
      else if (this.state === 'rejected') {
        setTimeout(() => {
          try {
            // 获取 onRejected 函数的返回值 x,并将其传递给 resolvePromise 处理
            const x = onRejected(this.reason);
            resolvePromise(promise2, x, resolve, reject);
          } catch (err) {
            reject(err);
          }
        });
      }
      // 当前 Promise 的状态为 pending 时,将 onFulfilled 和 onRejected 函数分别添加到数组中
      else {
        this.onResolvedCallbacks.push(() => {
          setTimeout(() => {
            try {
              // 获取 onFulfilled 函数的返回值 x,并将其传递给 resolvePromise 处理
              const x = onFulfilled(this.value);
              resolvePromise(promise2, x, resolve, reject);
            } catch (err) {
              reject(err);
            }
          });
        });

        this.onRejectedCallbacks.push(() => {
          setTimeout(() => {
            try {
              // 获取 onRejected 函数的返回值 x,并将其传递给 resolvePromise 处理
              const x = onRejected(this.reason);
              resolvePromise(promise2, x, resolve, reject);
            } catch (err) {
              reject(err);
            }
          });
        });
      }
    });

    return promise2;
  }

  catch(onRejected) {
    return this.then(null, onRejected);
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(new TypeError('Chaining cycle detected for promise'));
  }

  let called = false;

  if (x !== null && (typeof x === 'object' || typeof x === 'function')) {
    try {
      const then = x.then;

      if (typeof then === 'function') {
        then.call(
          x,
          y => {
            if (called) return;
            called = true;
            resolvePromise(promise2, y, resolve, reject);
          },
          r => {
            if (called) return;
            called = true;
            reject(r);
          }
        );
      } else {
        resolve(x);
      }
    } catch (err) {
      if (called) return;
      called = true;
      reject(err);
    }
  } else {
    resolve(x);
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值