Promise.finally实现

2021-08-09  本文已影响0人  Ag_fronted
Promise.prototype.myPromiseFinally = function (cb) {
  const P = this.constructor;
  return this.then(
    (value) => P.resolve(cb()).then(() => value),
    (reason) =>
      P.resolve(cb()).then(() => {
        throw reason;
      })
  );
};

new Promise((resolve, reject) => {
  //   resolve("success1");
  reject("error1");
})
  .myPromiseFinally(
    () =>
      new Promise((resolve) => {
        setTimeout(() => {
          console.log(111);
          resolve();
        }, 2000);
      })
  )
  .then((data) => {
    console.log(data);
  })
  .catch((error) => {
    console.log(error);
  });

上一篇 下一篇

猜你喜欢

热点阅读