在 promise 中 then 和 finally 有什么區(qū)別
看上去 promise.prototype.then() 和 promise.prototype.finally 似乎非常相似。但是你需要明白它們有一些重要的差異。
第一個也最明顯的是 finally() 沒有得到 promise 鏈的結(jié)果。由于 finally() 沒有收到值,因此無法更改 promise 的已解決值。
- new Promise((resolve, reject) => resolve(10))
- .then(x => {
- console.log(x); // 10
- return x + 1;
- })
- .finally(x => {
- console.log(x); // undefined
- return x + 2;
- });
- // Promise resolves to 11, the return value of then()
另一個差異與錯誤處理以及如何解決 promise 鏈有關(guān)。有時,您可能想要推遲捕獲 promise 鏈中的錯誤,從而允許你在其他地方處理。在這種情況下,promise 鏈的 then() 將不會被執(zhí)行,而 finally() 會。并且如果上一個 catch() 拋出,你最終會處于相同的情形之下。
- new Promise((resolve, reject) => reject(0))
- .catch(x => {
- console.log(x); // 0
- throw x;
- })
- .then(x => {
- console.log(x); // 將不會執(zhí)行
- })
- .finally(() => {
- console.log('clean up'); // 'clean up'
- });
- // Uncaught (in promise) 0
這里的重點是,除非有非常特殊的原因,否則不應(yīng)該替換 then() 和 finally()。 根據(jù)經(jīng)驗,finally() 應(yīng)該用于清理(清除超時,使引用為空,重置 UI 狀態(tài)等)。