簡單的 promise 實(shí)現(xiàn)

沒做catch,如果理解了下面代碼,catch不難實(shí)現(xiàn)。

const RESOLVED = "resolved";
const PENDING = "pending";

function MyPromise(fn) {
  this.status = PENDING;
  this.value = null;
  this.resolveCBs = [];

  // promise創(chuàng)建的時候的resolve函數(shù)
  const _resolve = (value) => {
    const that = this;
    // 如果resolve傳入的value是個promise,那么就把當(dāng)前的resolve傳給value.then
    // 等待value這個promise解決之后再執(zhí)行當(dāng)前resolve函數(shù)
    if (value instanceof MyPromise) {
      return value.then(_resolve);
    }
    this.status = RESOLVED;
    this.value = value;
    // 當(dāng)前promise完成,把掛在上面的callback全部執(zhí)行一遍
    this.resolveCBs.forEach((resolveCB) => {
      resolveCB(that.value);
    });
  };

  fn(_resolve);
}

// then函數(shù)要返回promise
MyPromise.prototype.then = function (onfulfilled) {
  const that = this;
  // 如果當(dāng)前promise還沒解決,創(chuàng)建一個新的promise,
  // 把新promise的resolve塞入resolveCBs數(shù)組
  // 同時把這個promise返回出去
  if (that.status === PENDING) {
    return new MyPromise((resolve) => {
      that.resolveCBs.push((val) => {
        resolve(onfulfilled(val));
      });
    });
  } else if (that.status === RESOLVED) {
    // 當(dāng)前promise已經(jīng)解決,直接將值傳過去
    let result = onfulfilled(that.value);
    if (result instanceof MyPromise) {
      return result;
    } else {
      return new MyPromise((resolve) => {
        resolve(that.value);
      });
    }
  }
};

let p = new MyPromise((resolve) => {
  setTimeout(() => {
    console.log(100);
    resolve(100);
  }, 1000);
})
  .then(
    (value) =>
      new MyPromise((resolve) => {
        setTimeout(() => {
          console.log(value + 1);
          resolve(value + 1);
        }, 1000);
      })
  )
  .then((value) => console.log(value + 1));

// 預(yù)期結(jié)果
// 0ms:
// 1000ms: 100
// 2000ms: 101 102
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。