ES6 承诺结算回调? [英] ES6 promise settled callback?
问题描述
无论我的 Promise 是否成功解决,我都想运行相同的操作.我不想将相同的函数绑定到 .then
的两个参数.难道没有像 jQuery 那样的 .always
吗?如果没有,我该如何实现?
I want to run the same action whether my Promise resolved successfully or not. I don't want to bind the same function to both args of .then
. Isn't there a .always
like jQuery has? If not, how do I achieve this?
推荐答案
难道没有像 jQuery 那样的
.always
吗?
不,(目前)没有.虽然有一个活动提案,所以也许是 ES2018.
是的,有:promise .finally()
是 ES2018 标准的一部分.
No, there's not (yet). Though there is an active proposal, so maybe ES2018.
Yes, there is: promise .finally()
is part of the standard since ES2018.
如果没有,我该如何实现?
If not, how do I achieve this?
您可以像这样自己实现 finally
方法:
You can implement the finally
method yourself like this:
Promise.prototype.finally = function(cb) {
const res = () => this
const fin = () => Promise.resolve(cb()).then(res)
return this.then(fin, fin);
};
或更广泛地,将解析信息传递给回调:
or more extensively, with passing resolution information to the callback:
Promise.prototype.finally = function(cb) {
const res = () => this
return this.then(value =>
Promise.resolve(cb({state:"fulfilled", value})).then(res)
, reason =>
Promise.resolve(cb({state:"rejected", reason})).then(res)
);
};
两者都确保保持原始分辨率(当回调中没有异常时)并等待承诺.
Both ensure that the original resolution is sustained (when there is no exception in the callback) and that promises are awaited.
这篇关于ES6 承诺结算回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!