自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

在 promise 中 then 和 finally 有什么區(qū)別

開發(fā) 前端
看上去 promise.prototype.then() 和 promise.prototype.finally 似乎非常相似。但是你需要明白它們有一些重要的差異。

看上去 promise.prototype.then() 和 promise.prototype.finally 似乎非常相似。但是你需要明白它們有一些重要的差異。

[[389960]]

第一個也最明顯的是 finally() 沒有得到 promise 鏈的結(jié)果。由于 finally() 沒有收到值,因此無法更改 promise 的已解決值。

  1. new Promise((resolve, reject) => resolve(10)) 
  2.   .then(x => { 
  3.     console.log(x); // 10 
  4.     return x + 1; 
  5.   }) 
  6.   .finally(x => { 
  7.     console.log(x); // undefined 
  8.     return x + 2; 
  9.   }); 
  10. // Promise resolves to 11, the return value of then() 

另一個差異與錯誤處理以及如何解決 promise 鏈有關(guān)。有時,您可能想要推遲捕獲 promise 鏈中的錯誤,從而允許你在其他地方處理。在這種情況下,promise 鏈的 then() 將不會被執(zhí)行,而 finally() 會。并且如果上一個 catch() 拋出,你最終會處于相同的情形之下。

  1. new Promise((resolve, reject) => reject(0)) 
  2.   .catch(x => { 
  3.     console.log(x); // 0 
  4.     throw x; 
  5.   }) 
  6.   .then(x => { 
  7.     console.log(x); // 將不會執(zhí)行 
  8.   }) 
  9.   .finally(() => { 
  10.     console.log('clean up'); // 'clean up' 
  11.   }); 
  12. // Uncaught (in promise) 0 

這里的重點是,除非有非常特殊的原因,否則不應(yīng)該替換 then() 和 finally()。 根據(jù)經(jīng)驗,finally() 應(yīng)該用于清理(清除超時,使引用為空,重置 UI 狀態(tài)等)。

 

責(zé)任編輯:趙寧寧 來源: 前端先鋒
相關(guān)推薦

2021-11-30 07:44:50

FinalFinallyFinalize

2021-12-10 12:01:37

finalfinallyfinalize

2022-08-31 08:33:54

Bash操作系統(tǒng)Linux

2025-04-18 10:36:15

2022-09-02 09:02:44

TypeInterface

2020-03-09 20:56:19

LoRaLoRaWAN無線技術(shù)

2022-09-07 18:32:57

并發(fā)編程線程

2020-11-09 14:07:53

PyQtQt編程

2022-06-06 14:53:02

LoRaLoRaWAN

2022-09-08 18:38:26

LinuxWindowsmacOS

2020-08-02 23:20:36

JavaScriptmap()forEach()

2021-12-17 14:40:02

while(1)for(;;)語言

2022-02-27 15:33:22

安全CASBSASE

2022-08-02 08:23:37

SessionCookies

2024-03-05 18:59:59

前端開發(fā)localhost

2024-05-27 00:40:00

2024-09-09 13:10:14

2021-05-16 14:26:08

RPAIPACIO

2025-04-27 08:15:00

FlinkSavepointCheckpoint

2023-11-01 08:08:47

PythonIS運算符
點贊
收藏

51CTO技術(shù)棧公眾號