ruanyf / es6tutorial

《ECMAScript 6入门》是一本开源的 JavaScript 语言教程,全面介绍 ECMAScript 6 新增的语法特性。
http://es6.ruanyifeng.com/
Other
21.26k stars 8.95k forks source link

Promise 对象一章关于 finally 的实现的问题 #1163

Closed bsc2xp closed 1 year ago

bsc2xp commented 1 year ago

文中对于 finally 的实现给出了示例:

Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value  => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};

这里为什么要使用 P.resolve(callback())?写成下面不行吗?

return this.then(
value => {try {callback();} catch(err){}; return value},
reason => {try {callback();} catch(err){}; throw reason }
);
ruanyf commented 1 year ago

此处不答疑