手写实现一个自己的promise

  function myPromise(constructor) {
    let self = this;
    self.status = "pending";
    self.value = undefined;
    self.reason = undefined;

    self.then = function (fullfill, reject) {
      switch(self.status){
        case "resolved":
          fullfill(self.value);
          break;
        case "rejected":
          reject(self.reason);
          break;
        default:
      }
      return this;
    };

    function resolve(value) {
      if (self.status === "pending") {
        self.value = value;
        self.status = "resolved";
      }
    }

    function reject(reason) {
      //两个==="pending",保证了状态的改变是不可逆的
      if (self.status === "pending") {
        self.reason = reason;
        self.status = "rejected";
      }
    }

    try {
      constructor(resolve, reject)
    } catch (e) {
      reject(e)
    }
  }

  let p = new myPromise((resolve, rej) => {
    resolve(1)
  }).then((x) => {
    console.log(x)
  }).then((x)=>{
    console.log(x);
  }).then((x)=>{
    console.log(x);
  })

结果:1,1,1

// 将.then方法单独实现
myPromise.prototype.then = function (fullfill, reject) {
  let self = this;
  switch(self.status){
    case "resolved":
      fullfill(self.value);
      break;
    case "rejected":
      reject(self.reason);
      break;
    default:
  }
};

你可能感兴趣的:(javascript)