Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

模拟实现一个 Promise.finally #25

Open
sihai00 opened this issue Jul 31, 2019 · 0 comments
Open

模拟实现一个 Promise.finally #25

sihai00 opened this issue Jul 31, 2019 · 0 comments
Assignees

Comments

@sihai00
Copy link
Owner

sihai00 commented Jul 31, 2019

模拟实现一个 Promise.finally

finally方法用于指定不管 Promise 对象最后状态如何,都会执行的操作。它的回调函数不接受任何参数,一般用于结束状态。

promise
.then(result => {···})
.catch(error => {···})
.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 })
  );
};

参考

ECMAScript 6 入门 - 阮一峰

@sihai00 sihai00 self-assigned this Jul 31, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant