[英]nested promise reject behaviour
我对 promise 有一些疑问:
这是我的 api 使用 axios 的函数:
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 块中,如果我返回某些东西被认为已解决,那么调用外部 function then()? 在这种情况下,唯一的方法是保持错误的传播在捕获中抛出异常?
谢谢
可能的解决方案:
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 })
所以在 catch 块中,如果我返回某些东西被认为已解决,那么调用外部 function then()?
是的。
在这种情况下,唯一的方法是保持错误的传播在捕获中抛出异常?
我建议不要将.catch()
放在_get
中。 相反,写
function callDoStuff(id: number) {
doStuff(id).then(() => {
notification.success({ message: 'Success', description: 'Template deleted!' });
}, (error: Error) => {
notification.error({ message: 'Error', description: error.message })
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.