手写Promise源码

535 阅读3分钟
  1. Promise就是一个类,在执行这个类的时候需要传递一个执行器进去,执行器会立即执行
  2. Promise中有三种状态,分别为成功fulfilled、失败rejected以及等待pending 
  3. then方法内部做的事情就判断状态,如果状态是成功则调用成功的回调函数,如果状态是失败则调用失败的回调函数,then方式是被定义在原型对象中的
  4. then成功回调有一个参数,表示成功之后的值,then失败回调有一个参数,表示失败后的原因
  5. 同一个promise对象下面的then方法是可以被调用多次的
  6. then方法是可以被链式调用的, 后面then方法的回调函数拿到值的是上一个then方法的回调函数的返回值
const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject);
    } catch {
      this.reject(e);
    }
  }

  // promise 状态
  status = PENDING;
  // 成功之后的值
  value = undefined;
  // 失败之后的原因
  reason = undefined;
  // 成功回调
  successCallback = [];
  // 失败回调
  failCallback = [];

  resolve = (value) => {
    // 如果状态不是等待,阻止代码向下执行
    if (this.status !== PENDING) return;
    // 将状态变更为成功
    this.status = FULFILLED;
    // 保存成功之后的值
    this.value = value;
    // 判断成功回调是否存在,如果存在则调用
    // this.successCallback && this.successCallback(this.value)
    while (this.successCallback.length) this.successCallback.shift()();
  };

  reject = (reason) => {
    // 如果状态不是等待,阻止代码向下执行
    if (this.status !== PENDING) return;
    // 将状态变更为失败
    this.status = REJECTED;
    // 保存失败之后的原因
    this.reason = reason;
    // 判断失败回调是否存在,如果存在则调用
    // this.failCallback && this.successCallback(this.reason)
    while (this.failCallback.length) this.failCallback.shift()();
  };

  then(successCallback, failCallback) {
    successCallback = successCallback ? successCallback : value => value
    failCallback = failCallback ? failCallback : reason => {throw reason}
    let promise2 = new MyPromise((resolve, reject) => {
      // 判断状态
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);
            // 判断 x 的值是普通值还是promise对象
            // 如果是普通值则直接调用resolve
            // 如果是promise对象,查看promise对象返回的结果
            // 再根据promise对象返回的结果,决定调用resolve还是调用reject
            resolvePromise(promise2, x, resolve, reject);
          } catch(e) {
            reject(e);
          }
        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);
            // 判断 x 的值是普通值还是promise对象
            // 如果是普通值则直接调用resolve
            // 如果是promise对象,查看promise对象返回的结果
            // 再根据promise对象返回的结果,决定调用resolve还是调用reject
            resolvePromise(promise2, x, resolve, reject);
          } catch(e) {
            reject(e);
          }
        }, 0);
      } else {
        // 等待
        // 将成功回调和失败回调存储起来
        this.successCallback.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              // 判断 x 的值是普通值还是promise对象
              // 如果是普通值则直接调用resolve
              // 如果是promise对象,查看promise对象返回的结果
              // 再根据promise对象返回的结果,决定调用resolve还是调用reject
              resolvePromise(promise2, x, resolve, reject);
            } catch(e) {
              reject(e);
            }
          }, 0);
        });
        this.failCallback.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              // 判断 x 的值是普通值还是promise对象
              // 如果是普通值则直接调用resolve
              // 如果是promise对象,查看promise对象返回的结果
              // 再根据promise对象返回的结果,决定调用resolve还是调用reject
              resolvePromise(promise2, x, resolve, reject);
            } catch(e) {
              reject(e);
            }
          }, 0);
        });
      }
    });
    return promise2;
  }
}

function resolvePromise(promise2, x, resolve, reject) {
  if (promise2 === x) {
    return reject(
      new TypeError("Chaining cycle detected for promise #<Promise>")
    );
  }
  if (x instanceof MyPromise) {
    // promise 对象
    // x.then(value=>resolve(value),reason=>reject(reason))
    x.then(resolve, reject);
  } else {
    // 普通值
    resolve(x);
  }
}

module.exports = MyPromise;