antd 升级到umi后,也没有对request做超时处理,很奇怪
因fetch本身不支持超时,这里需要用到Promise.race()方法
Promise.race([p1,p2,p3])
p1,p2,p3哪个快,就得到的是哪个
Promise.race([
fetch(url,options),
new Promise((resolve, reject)=> {
setTimeout(()=> reject(new Error('request timeout')), 30000)
})
]).then((res)=>{
}).catch((e)=>{
})
antd 的request.js 返回值改造成这样
return Promise.race([
fetch(url, newOptions),
new Promise((resolve, reject)=> {
setTimeout(()=> reject(new Error('request timeout')), 30000)
})])
.then(checkStatus)
.then(response => {
if (newOptions.method === 'DELETE' || response.status === 204) {
return response.text();
}
return response.json();
})
.catch(e => {
if (e && e.message.match && e.message.match(/timeout/)) {
notification.error({
key: 'timeout',
message: `请求超时`,
description: ' ',
});
return;
}
const status = e.name;
if (status === 403) {
router.push('/exception/403');
return;
}
if (status <= 504 && status >= 500) {
router.push('/exception/500');
return;
}
if (status >= 404 && status < 422) {
router.push('/exception/404');
}
});
由于fetch不支持中断,这里只是前端拿到一个超时状态,请求还是会继续,不会中断。