Fetch API 是现代浏览器提供的用于发起网络请求的接口,它基于 Promise,比传统的 XMLHttpRequest 更简洁强大。默认情况下,Fetch API 没有内置的超时机制,这意味着如果服务器不响应,请求可能会无限期挂起。
const controller = new AbortController();
const signal = controller.signal;
// 设置超时时间
const timeout = 5000; // 5秒
// 设置超时定时器
const timeoutId = setTimeout(() => {
controller.abort();
console.log('请求超时');
}, timeout);
fetch('https://api.example.com/data', { signal })
.then(response => {
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => {
console.log('成功获取数据:', data);
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('请求被中止:', error);
} else {
console.log('请求错误:', error);
}
});
function fetchWithTimeout(url, options, timeout = 5000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('请求超时')), timeout)
)
]);
}
fetchWithTimeout('https://api.example.com/data', {}, 5000)
.then(response => {
if (!response.ok) {
throw new Error('网络响应不正常');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('错误:', error));
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 8000 } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal
});
clearTimeout(id);
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
return response;
}
// 使用示例
fetchWithTimeout('https://api.example.com/data', { timeout: 5000 })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('错误:', error));