Promise状态、原因(二)

61 阅读1分钟

image.png

  1. Promise 有pending、fulfilled、rejected 三种状态
  2. Promise 的状态只能从 pending 到 fulfilled 或 rejected,一旦状态敲定,就不可以更改了
  <script>
    const PENDING = "pending";
    const FULFILLED = "fulfilled";
    const REJECTED = "rejected";
    class FXPromise {
      // 1. 添加状态
      state = PENDING;
      // 2. 添加原因
      result = undefined;

      constructor(fn) {
        const resolveFunc = (res) => {
          // 3.没有敲定状态,就敲定状态,以及添加原因
          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);
      }
    }

    new FXPromise((resolve, reject) => {
      console.log(1);
      reject(222);
      resolve(111);
    });
  </script>

image.png