【发布时间】:2021-03-14 08:21:48
【问题描述】:
我对承诺有些怀疑:
这是我使用 axios 的 api 函数:
const _get = (url: string) => axios
.get(url)
.then((response: { data: responseData }) => {
if (response) {
console.log(response)
const { data, status, message } = response.data;
if (status) {
return data
} else {
throw new Error(message);
}
}
})
//notification is an antd component to show a toast with the error
.catch((error: Error) => notification.error({ message: 'Error', description: error.message }));
export const doStuff = (id: number) =>_get('/api/do/${id}');
当我调用 api 以防出错时调用 then()
const callDoStuff = (id: number) => {
doStuff(id).then(() => {
//called also if doStuff catch() is resolved
notification.success({ message: 'Success', description: 'Template deleted!' });
});
};
所以在 catch 块中,如果我返回的东西被认为已解决,那么外部函数 then() 会被调用吗?在这种情况下,唯一的方法是保持错误的传播并在 catch 中抛出异常?
谢谢
可能的解决方案:
const _get = (url: string) => axios
.get(url)
.then((response: { data: responseData }) => {
if (response) {
console.log(response)
const { data, status, message } = response.data;
if (status) {
return data
} else {
throw new Error(message);
}
}
})
使用特定的捕获器处理 then() 错误
const callDoStuff = (id: number) => {
doStuff(id)
.then((response) => {// success handler}, e=>{// specific error thrown by the inner then })})
.catch(e=>{//axios error })
使用通用捕捉器处理错误
const callDoStuff = (id: number) => {
doStuff(id)
.then((response) => { //success handler })
.catch(e=>{ // generic error handler })
【问题讨论】:
标签: javascript promise async-await axios