美文网首页
Promise.finally实现

Promise.finally实现

作者: Ag_fronted | 来源:发表于2021-08-09 16:21 被阅读0次
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);
  });

相关文章

网友评论

      本文标题:Promise.finally实现

      本文链接:https://www.haomeiwen.com/subject/suizvltx.html