蓝知更鸟提供了一个finally方法,无论在您的承诺链中发生什么,它都被称为。我发现它非常方便清理目的(比如打开资源,隐藏加载程序,.)
ES6本机承诺中是否有类似的内容?
发布于 2016-03-14 22:14:50
截至2018年2月7日
Chrome 63+、火狐58+和Opera 50+支持Promise.finally。
在Node.js 8.1.4+ (V8 5.8+)中,标志--harmony-promise-finally后面有此特性。
Promise.prototype.finally ECMAScript提案当前处于TC39进程的第三阶段中。
同时,为了在所有浏览器中都具有promise.finally功能,可以在 catch() 之后添加一个额外的,以始终调用回调。
示例:
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库。
https://stackoverflow.com/questions/35999072
复制相似问题