ES6承诺解决回调? [英] ES6 promise settled callback?
问题描述
.then
的两个args。是不是有一个 .always
像jQuery有?如果没有,我该如何实现?
没有一个
.always
like jQuery has?
如果没有,我该如何实现?
你可以实现终于
方法本身就是这样的:
Promise.prototype.finally = function(cb){
const res =()=>这个
const fin =()=> promise.resolve(cb())。then(res)
return this.then(fin,fin);
};
或更广泛地将传递的解析信息传递给回调:
Promise.prototype.finally = function(cb){
const res =()=>这个
返回this.then(value =>
Promise.resolve(cb({state:fulfilled,value}))然后(res)
,reason =>
Promise.resolve(cb({state:rejected,reason}))然后(res)
);
};
两者都确保原始解决方案得到持续(当回调中没有例外),并且承诺等待着。
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?
Isn't there a
.always
like jQuery has?
No, there's not (yet). Though there is an active proposal, so maybe ES2018.
If not, how do I achieve this?
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屋!