



















Jordan Harband 提出了 Promise.prototype.finally 这一章节的提案。
.finally() 这样用:
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
finally 的回调总是会被执行。作为比较:
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();
});
同步代码里,try 语句分为三部分:try 分句,catch 分句和 finally 分句。
对比 Promise:
然而,finally {} 可以 return 和 throw ,而在.finally() 回调里只能 throw, return 不起任何作用。这是因为这个方法不能区分显式返回和正常结束的回调。
promise.prototype.finally 是 .finally() 的一个 polyfill原文:http://exploringjs.com/es2018-es2019/ch_promise-prototype-finally.html
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。