无论我的Promise是否成功解决,我都想执行相同的操作。我不想将相同的功能绑定(bind)到.then的两个参数。是否没有jQuery一样的.always?如果没有,我该如何实现?

最佳答案


不,there's not (yet)。虽然有一个active proposal,但也许是ES2018。
是的,有:promise .finally() 自ES2018起已成为标准的一部分。

您可以自己实现finally方法,如下所示:

Promise.prototype.finally = function(cb) {
    const res = () => this
    const fin = () => Promise.resolve(cb()).then(res)
    return this.then(fin, fin);
};
或更广泛地讲,将解析信息传递给回调:
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)
    );
};
两者都确保原始解析得以维持(当回调中没有异常时),并确保等待 promise 。

关于javascript - ES6 promise 解决回调,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32362057/

10-12 00:08
查看更多