亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對失敗的承諾使用 then()?

對失敗的承諾使用 then()?

RISEBY 2022-11-03 15:01:01
我有一個存儲方法...async store() {      try {         return await axios.post('/upload', data);      } catch (error) {                     }  },調用者:store().then(()=>{ console.log('ok'); }, ()=>{ console.log('not ok'); });但是當 store 方法失敗并捕獲到錯誤時,then總是調用第一個方法,如何才能not ok調用失敗的方法?
查看完整描述

1 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

您需要在函數塊中throw捕獲的錯誤catchstore


async store() {

    try {

       return await axios.post('/upload', data);

    } catch (error) {

       throw error;  

    }

}

您也可以跳過捕獲函數中的錯誤,并在store調用函數時簡單地捕獲它store。為此,您只需要返回axios.post(...).


async store() { 

   return axios.post('/upload', data);

}

(注意,沒有這個try-catch塊,你不需要一個awaitbeforeaxios.post(...)因為store函數返回的 promise 將被解析為返回的 promise axios.post(...)。這意味著如果返回的 promiseaxios.post(...)被履行,store函數返回的 promise 也將履行具有與履行返回的承諾相同的履行價值axios.post(...)。)


將第二個參數傳遞給then函數是不常見的。相反,您應該鏈接一個.catch()塊來捕獲錯誤。


store()

  .then(() => console.log('ok'))

  .catch(() => console.log('not ok'));


查看完整回答
反對 回復 2022-11-03
  • 1 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號