ghostjzf / handwrite-impletaion

前端需要知道的一些需要手写实现
0 stars 0 forks source link

实现Promise #1

Open ghostjzf opened 4 years ago

ghostjzf commented 4 years ago
const PENDING = "pendding";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

function MyPromise(excutor) {
  this.status = PENDING;
  this.value = null;
  this.reason = null;

  this.resolveCollect = [];
  this.rejectCollect = [];

  const resolve = (value) => {
    this.value = value;
    this.status = FULFILLED;

    this.resolveCollect.forEach((callback) => {
      const _value = callback(value);

      this._value = _value;
    });
  };

  const reject = (reason) => {
    this.reason = reason;
    this.status = REJECTED;
  };

  if (typeof excutor === "function") {
    excutor(resolve, reject);
  }
}

MyPromise.prototype.then = function(onFulfilled, onRejected) {
  if (this.status === PENDING) {
    return new MyPromise((resolve, reject) => {
      this.resolveCollect.push((value) => {
        let x = onFulfilled(value);

        if (x instanceof MyPromise) {
          return x.then(resolve);
        }

        resolve(x);
      });
    });
  }

  if (this.status === FULFILLED) {
    return new MyPromise((resolve) => {
      let x = onFulfilled(this.value);

      if (x instanceof MyPromise) {
        return x.then(resolve);
      }

      resolve(x);
    });
  }

  //   return new MyPromise((resolve) => {
  //     let x = onFulfilled(this.value);

  //     if (x instanceof MyPromise) {
  //       x.then(resolve);
  //     }

  //     resolve(x);
  //   });
};

var p1 = new MyPromise((resolve) => {
  console.log(111);

  setTimeout(() => {
    resolve(222);
  }, 2000);
});

p1.then((res) => {
  console.log(res);
})
  .then((res) => {
    console.log("stage2:", res);

    return 333;
  })
  .then((res) => {
    console.log("stage3:", res);
  });