簡體   English   中英

如何處理異步 javascript function 中的多個承諾?

[英]how to handle multiple promises in async javascript function?

請參見下面的示例,我有一個異步 function,我想添加一個 fetch 調用並確保它在調用另一個 function getCustomerData 之前返回,它返回一個 ZB321DE3BDC299EC807E9F795D7D7。 我如何確保我的第一個 api 調用被返回並完成,我打了第二個電話。 我在測試中注意到下面的代碼會產生錯誤,因為它看起來像是在第一次調用完成/返回之前執行第二次調用。

async function getRecords() {
   
   //first api call
   fetch('api/getCustomerDetails', options).then(). catch(); 

   //second call 
   let response = await getCusotomerData().promise(); 
}

您只需要添加 await,async function 沒有它就沒有任何意義,它只是等待 awaits 關鍵字之后的每個進程完成,然后再轉到下一行代碼。

then() 和 catch() 將根據 fetch 的值執行,但它們不控制代碼的執行。 例如,您可以將第二行放在 then() 中,它的工作方式與 await 相同。

通常你使用 await 或 then & catch

async function getRecords() {
   
   //first api call
   await fetch('api/getCustomerDetails', options).then().catch(); 

   //second call 
   let response = await getCusotomerData().promise(); 
}
async function fn() {       // asynchronous function
   
   await process_a          // the await will not allow anything to happen before process_a finishs

   process_b                // this will wait for process_a to finish
}

你仍然需要驗證process_a的結果,所以使用它的try & catch

async function getRecords() {
   
   //first api call
   fetch('api/getCustomerDetails', options).then(()=>{
         //second call in case first one is success
         let response = await getCusotomerData().promise(); 
         }).catch(()=>{
             //handle first api call errors here
         });
}

或在下面的答案中使用 try catch 塊

很多方法可以做到這一點。 我認為最干凈的是 try/catch

async function getRecords() {
   try{
       await fetch('api/getCustomerDetails', options)
       let response = await getCusotomerData().promise(); 
   } catch(e) {
       // error handling here
   }
}

fetch調用之前使用await可確保在 fetch promise 完成之前不會執行以下行。 您可能希望有更具體的錯誤捕獲邏輯,因為上述塊將捕獲整個 try 塊中出現的任何問題,但您可能希望在更精細的級別上捕獲錯誤(即.catch用於獲取)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM