ES6承诺解决回调? [英] ES6 promise settled callback?

查看:136
本文介绍了ES6承诺解决回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要运行相同的动作,无论我的承诺是否成功解决。我不想将相同的函数绑定到 .then 的两个args。是不是有一个 .always 像jQuery有?如果没有,我该如何实现?

解决方案


没有一个 .always like jQuery has?


否,还没有(还)。虽然积极的提案,也许是ES2018。


如果没有,我该如何实现?


你可以实现终于方法本身就是这样的:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆