axios 超时后收到通知 [英] Get notified after axios timeout
本文介绍了axios 超时后收到通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用 axios 的 API 调用.超时设置为 2500 毫秒.我想要的是 axios 在超时后返回一个值,以便我可以通知用户请求由于某些服务器或网络错误而中止.
I have an API call using axios. A timeout is set for 2500 millis. What I want is axios to return a value after the timeout so I can notify to the user the request is aborted due to some server or network error.
我如何初始化超时
const instance = axios.create();
instance.defaults.timeout = 2500;
下面是超时后应该返回值的函数
Below is the function that should return a value after the timeout
_post(url, body, token) {
return new Promise((resolve, reject) => {
instance
.post(url, body, {headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}})
.then(data => {
resolve(data);
})
.catch(error => {
reject(error);
});
});
}
谢谢!
推荐答案
Axios 错误由 code
属性.
Axios errors are identified by code
property.
这是ECONNABORTED
代码,以防超时.
It's ECONNABORTED
code in case of a timeout.
上面的代码使用了promise构造反模式.已经有promise了,不用再新建一个:
The code above uses promise construction antipattern. There's already a promise, no need to create a new one:
_post(url, body, token) {
return instance
.post(url, body, {headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}})
.catch(error => {
if (error.code === 'ECONNABORTED')
return 'timeout';
else
throw error;
});
}
这篇关于axios 超时后收到通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文