【问题标题】:What is the equivalent of Bluebird Promise.finally in native ES6 promises? [duplicate]原生 ES6 承诺中 Bluebird Promise.finally 的等价物是什么? [复制]
【发布时间】:2016-06-30 04:07:55
【问题描述】:

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

在 ES6 原生 Promise 中有等价物吗?

【问题讨论】:

标签: javascript promise bluebird


【解决方案1】:

截至 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 Proposal 目前在 TC39 进程的stage 3 中。

同时在所有浏览器中都有 promise.finally 功能; 您可以在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 库。

【讨论】:

  • 值得一提的是,这个 .catch() 不仅会捕获原始 Promise 的失败,还会捕获原始 .then() 处理程序中抛出的所有错误。因此,使用此代码很容易意外抑制某些错误消息。
  • if (Promise.prototype.finally == undefined) { Promise.prototype.finally = function (callback) { return this.then(function (result) { return Promise.resolve(callback()) .then(function () { return result; }); }, function (error) { return Promise.resolve(callback()).then(function () { throw error; }); }); }; }
  • 为什么不推荐使用prototype.finally 方法?
  • 我花了一段时间才弄清楚finally 应该如何接收参数作为状态,无论承诺如何解决/拒绝Promise.prototype.finally = function(cb) { const res = () => this const fin = (value) => Promise.resolve(cb(value)).then(res) return this.then(fin, fin)
  • @JanHommes 从不建议使用自定义方法扩展原型。当规范决定添加 .finally() 的本机实现或您添加到原型的任何方法时,您最终会遇到一个损坏的实现,并且您的应用可能会停止在较新的浏览器上运行。
猜你喜欢
  • 2015-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
相关资源
最近更新 更多