function fetchData() {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
clearTimeout(timer);
reject(new Error('Timeout'));
}, 5000);
fetch('https://example.com/api/data')
.then(response => {
clearTimeout(timer);
resolve(response.json());
})
.catch(error => {
clearTimeout(timer);
reject(error);
});
});
}
fetchData()
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Error:', error);
});
具体的实现思路如下:
- 定义一个
fetchData函数,该函数返回一个 Promise 对象。 - 在
fetchData函数中使用setTimeout函数设置一个 5s 的定时器,如果请求未在 5s 内完成,则会触发定时器的回调函数并抛出一个超时的错误。 - 在
fetchData函数中使用fetch函数发起异步请求,并使用 Promise 的then和catch方法来处理请求的响应结果或错误。 - 在
fetch的then方法中,首先清除之前设置的定时器,然后将响应的数据解析为 JSON 格式并返回。 - 在
fetch的catch方法中,首先清除之前设置的定时器,然后将错误抛出。 - 在主函数中调用
fetchData函数,使用then方法处理请求的响应结果,使用catch方法处理请求的错误。
这种实现方式使用了 Promise 来处理异步请求,并使用 setTimeout 来实现 5s 超时的效果,同时通过 then 和 catch 方法处理请求的响应结果或错误。这样就可以在请求未完成的情况下终止请求,并返回一个超时的错误,避免了程序的长时间等待。