本章主要解释由Jordan Harband提出的"Promise.prototype.finally"提案。
它是如何工作的?
.finally()工作如下:
promise
.then(result => {...})
.catch(error => {...})
.finally(() => {...});finally的回调总是被执行的。比较:
只有promise成功完成时,才会执行then回调
只有promise被拒绝,才会执行catch回调。如then的回调抛出异常或返回被拒绝的promise。
比如下面这段代码
promise
.finally(() => {
«statements»
});上面这段代码相当于:
promise
.then( result => {
«statements» return result;
}, error => {
«statements» throw error;
}
);用例
常见的用例与同步finally子句中常见的用例类似:在完成资源处理后进行清理。无论一切进展顺利还是出现错误,总会发生这种情况。
例如:
let connection;
db.open()
.then(conn => {
connection = conn; return connection.select({name:'Jane'});
})
.then(result => { // Process result
// Use `connection` to make more queries})
...
.catch(error => { // handle errors}).finally(() => {
connection.close();
});finally()在同步代码中与finally {}类似
在同步代码中,try语句由三部分组成:try子句,catch子句和finally子句。
在promise中:
try子句大概相当于调用基于Promise的函数或调用.then()。
catch子句对应于Promises的.catch()方法。
finally子句对应于提案引入的新的Promise方法.finally()。
可用性
.finally()的polyfill promise.prototype.finally npm包
V8 5.8+(例如在Node.js 8.1.4+中):可用的标记 --harmony-promise-finally(详情)
随时随地看视频