Jordan Harband 提出了 Promise.prototype.finally
這一章節(jié)的提案疹吃。
如何工作?
.finally() 這樣用:
promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});
finally 的回調(diào)總是會(huì)被執(zhí)行暴心。作為比較:
- then 的回調(diào)只有當(dāng) promise 為 fulfilled 時(shí)才會(huì)被執(zhí)行胖秒。
- catch 的回調(diào)只有當(dāng) promise 為 rejected,或者 then 的回調(diào)拋出一個(gè)異常抑胎,或者返回一個(gè) rejected Promise 時(shí)梨撞,才會(huì)被執(zhí)行雹洗。
換句話說(shuō)香罐,下面的代碼段:
promise
.finally(() => {
?statements?
});
等價(jià)于:
promise
.then(
result => {
?statements?
return result;
},
error => {
?statements?
throw error;
}
);
使用案例
最常見(jiàn)的使用案例類(lèi)似于同步的 finally 分句:處理完某個(gè)資源后做些清理工作。不管是一切正常时肿,還是出現(xiàn)了錯(cuò)誤庇茫,這樣的工作都是有必要的。
舉個(gè)例子:
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() 類(lèi)似于同步代碼中的 finally {}
同步代碼里螃成,try 語(yǔ)句分為三部分:try 分句旦签,catch 分句和 finally 分句。
對(duì)比 Promise:
- try 分句相當(dāng)于調(diào)用一個(gè)基于 Promise 的函數(shù)或者 .then() 方法
- catch 分句相當(dāng)于 Promise 的 .catch() 方法
- finally 分句相當(dāng)于提案在 Promise 新引入的 .finally() 方法
然而锈颗,finally {} 可以 return 和 throw 顷霹,而在.finally() 回調(diào)里只能 throw, return 不起任何作用。這是因?yàn)檫@個(gè)方法不能區(qū)分顯式返回和正常結(jié)束的回調(diào)击吱。
可用性
-
npm 包
promise.prototype.finally
是 .finally() 的一個(gè) polyfill - V8 5.8+ (比如. Node.js 8.1.4+):加上 --harmony-promise-finally 標(biāo)記后可用淋淀。(了解更多)
深入閱讀
原文:http://exploringjs.com/es2018-es2019/ch_promise-prototype-finally.html