Javascript 原生 ES6 承诺中 Bluebird Promise.finally 的等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35999072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:29:34  来源:igfitidea点击:

What is the equivalent of Bluebird Promise.finally in native ES6 promises?

javascriptpromisebluebird

提问by Aric Lasry

Bluebird offers a finallymethod that is being called whatever happens in your promise chain. I find it very handy for cleaning purposes (like unlocking a resource, hiding a loader, ...)

Bluebird 提供了一种finally方法,无论您的承诺链中发生什么,它都会被调用。我发现它用于清理目的非常方便(例如解锁资源,隐藏加载程序,......)

Is there an equivalent in ES6 native promises?

ES6 原生 Promise 中是否有等价物?

回答by Miguel Mota

As of February 7, 2018

截至 2018 年 2 月 7 日

Chrome 63+, Firefox 58+, and Opera 50+ support Promise.finally.

支持 Chrome 63+、Firefox 58+ 和 Opera 50+ Promise.finally

In Node.js 8.1.4+ (V8 5.8+), the feature is available behind the flag --harmony-promise-finally.

在 Node.js 8.1.4+ (V8 5.8+) 中,该功能在 flag 后面可用--harmony-promise-finally

The Promise.prototype.finally ECMAScript Proposalis currently in stage 3of the TC39 process.

所述Promise.prototype.finally ECMAScript的提案是目前在阶段3的TC39过程。

In the meantime to have promise.finally functionality in all browsers; you can add an additional then()after the catch()to always invoke that callback.

同时在所有浏览器中都有 promise.finally 功能;您可以then()catch()始终调用该回调之后添加一个额外的

Example:

例子:

myES6Promise.then(() => console.log('Resolved'))
            .catch(() => console.log('Failed'))
            .then(() => console.log('Always run this'));

JSFiddle Demo: https://jsfiddle.net/9frfjcsg/

JSFiddle 演示:https://jsfiddle.net/9frfjcsg/

Or you can extend the prototype to include a finally()method (not recommended):

或者您可以扩展原型以包含一个finally()方法(不推荐):

Promise.prototype.finally = function(cb) {
    const res = () => this;
    const fin = () => Promise.resolve(cb()).then(res);
    return this.then(fin, fin);
};

JSFiddle Demo: https://jsfiddle.net/c67a6ss0/1/

JSFiddle 演示:https://jsfiddle.net/c67a6ss0/1/

There's also the Promise.prototype.finallyshim library.

还有Promise.prototype.finally垫片库。