gpt4 book ai didi

javascript - 原生 ES6 promise 中 Bluebird Promise.finally 的等价物是什么?

转载 作者:IT老高 更新时间:2023-10-28 13:17:10 26 4
gpt4 key购买 nike

Bluebird 提供 finally无论您的 promise 链中发生什么,都会调用该方法。我发现它对于清理目的非常方便(比如解锁资源、隐藏加载器......)

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

最佳答案

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

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

例子:

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

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

或者您可以扩展原型(prototype)以包含 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垫片库。

关于javascript - 原生 ES6 promise 中 Bluebird Promise.finally 的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35999072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com