蓝鸟承诺是什么等价物,最后在原生ES6承诺中

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

本文关键字:承诺 原生 ES6 是什么 等价物 蓝鸟 最后      更新时间:2023-09-26

Bluebird提供了一种finally方法,无论在承诺链中发生什么,都可以调用它。我发现它对于清洁目的非常方便(例如解锁资源、隐藏加载器......

ES6 原生承诺中是否有等效项?

截至2018年2月7日

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

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

Promise.prototype.finally ECMAScript 提案目前处于 TC39 流程的第 3 阶段。

同时要有希望,终于在所有浏览器中具有功能;您可以在catch()后添加额外的then(),以始终调用该回调

例:

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

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

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

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

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

还有 Promise.prototype.finally shim 库。