这个问题在这里已有答案:
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 Proposal目前在TC39进程的stage 3。
同时在所有浏览器中都有承诺。最终功能;您可以在then()
之后添加额外的catch()
以始终调用该回调。
例:
myES6Promise.then(() => console.log('Resolved'))
.catch(() => console.log('Failed'))
.then(() => console.log('Always run this'));
JSぇdでも但是:z zxswい
或者您可以扩展原型以包含https://jsfiddle.net/9frfjcsg/方法(不推荐):
finally()
JSぇdでも但是:z zxswい
还有Promise.prototype.finally = function(cb) {
const res = () => this;
const fin = () => Promise.resolve(cb()).then(res);
return this.then(fin, fin);
};
垫片库。