Promise then的成功失败回调(三)

39 阅读1分钟

image.png

  1. then 方法最多接受两个参数:用于 Promise 兑现和拒绝情况的回调函数。
  2. then 方法参数不是function类型的处理
    const PENDING = "pending";
    const FULFILLED = "fulfilled";
    const REJECTED = "rejected";
    class FXPromise {
      state = PENDING;
      result = undefined;

      constructor(fn) {
        const resolveFunc = (res) => {
          if (this.state === PENDING) {
            this.result = res;
            this.state = FULFILLED;
            console.log("resolve ", res);
          }
        };
        const rejectFunc = (res) => {
          if (this.state === PENDING) {
            this.result = res;
            this.state = REJECTED;
            console.log("reject ", res);
          }
        };
        fn(resolveFunc, rejectFunc);
      }

      // 1. 添加实例方法
      then(onFulfilled, onRejected) {
        // 2. 参数判断(参考文档)
        onFulfilled =
          typeof onFulfilled === "function" ? onFulfilled : (x) => x;
        onRejected =
          typeof onRejected === "function"
            ? onRejected
            : (x) => {
                throw x;
              };
        // 2.1 执行成功回调
        // 2.2 执行失败回调
        if (this.state === FULFILLED) {
          onFulfilled(this.result);
        } else if (this.state === REJECTED) {
          onRejected(this.result);
        } else if (this.state === PENDING) {
          // ... 待定
        }
      }
    }

    new FXPromise((resolve, reject) => {
      reject(222);
      resolve(111);
    }).then(
      (res) => {
        console.log("then res ", res);
      },
      (err) => {
        console.log("then err ", err);
      }
    );

image.png