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'));
添加回答
舉報
0/150
提交
取消
