js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

2. 实现Promise.finally

Open Sunny-117 opened this issue 3 years ago • 4 comments

/**
   * 无论成功还是失败都会执行回调
   * @param {Function} onSettled
   */
 Promise.prototype.finally = function (onSettled) {
    return this.then(
      (data) => {
        onSettled(); // 实现了收不到参数了
        return data;
      },
      (reason) => {
        onSettled();
        throw reason;
      }
    );
    // finally函数 返回结果应该是无效的
  }
  
/******test finally*******/
// 无论什么结果,都会运行
const pro = new Promise((resolve, reject) => {
  resolve(1);
});
const pro2 = pro.finally((d) => {
  console.log("finally", d); // 收不到d参数
  // 本身不改变状态,但是抛出一个错误,数据就会变成它的错误
  // throw 123;
  return 123; //不起作用
});
setTimeout(() => {
  console.log(pro2);
});

Sunny-117 avatar Nov 03 '22 06:11 Sunny-117

Promise.prototype.myfinally = function (cb) {
  return this.then(
    async (data) => {
      await Promise.resolve(cb(data));
      return data;
    },
    async (err) => {
      await Promise.resolve(cb(err));
      throw err;
    }
  );
};

const pro = new Promise((resolve, reject) => {
  resolve(1);
});
const pro2 = pro.myfinally((d) => {
  console.log("finally", d); // 收不到d参数
  // 本身不改变状态,但是抛出一个错误,数据就会变成它的错误
  // throw 123;
  return 123; //不起作用
});

weirong111 avatar Nov 06 '22 07:11 weirong111

Promise.prototype.myfinally = function (callback) {
  return this.then(
    async (res) => {
      await callback();
      return res; //finally本质起传递的作用,这里的res是上一个then函数的返回值
    },
    async (err) => {
      await callback();
      throw err;
    }
  );
};

Promise.resolve(123)
  .then((res) => {
    console.log(res); //123
    return Promise.reject(456);
  })
  .myfinally(() => {
    console.log("finally");
    return "finally本身不返回值";
  })
  .then(
    () => {},
    (err) => {
      console.log(err); //123
      return 789;
    }
  )
  .myfinally(() => console.log("finally"))
  .then((res) => console.log(res)); //789

YMnotafraid avatar Mar 03 '23 15:03 YMnotafraid

Promise.prototype.Finally = function (fn) { return new Promise((resolve, reject) => { this.then((data) => { fn(); resolve(data); }).catch((err) => { fn(); reject(err); }); }); };

cscty avatar Jun 18 '23 08:06 cscty

Promise.prototype.myfinally = function (callback) {
  return this.then(
    value => {
      return Promise.resolve(callback()).then(value => value)
    },
    err => {
      return Promise.reject(callback()).then(() => {throw err})
    } 
  );
};

Windseek avatar Nov 08 '24 02:11 Windseek