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

半腔热情 提交于 2019-12-17 17:26:26

问题


Bluebird offers a finally method 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, ...)

Is there an equivalent in ES6 native promises?


回答1:


As of February 7, 2018

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

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

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

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.

Example:

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

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

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

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/

There's also the Promise.prototype.finally shim library.



来源:https://stackoverflow.com/questions/35999072/what-is-the-equivalent-of-bluebird-promise-finally-in-native-es6-promises

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!