请求 5s 未完成就终止

403 阅读1分钟
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 的 thencatch 方法来处理请求的响应结果或错误。
  • fetchthen 方法中,首先清除之前设置的定时器,然后将响应的数据解析为 JSON 格式并返回。
  • fetchcatch 方法中,首先清除之前设置的定时器,然后将错误抛出。
  • 在主函数中调用 fetchData 函数,使用 then 方法处理请求的响应结果,使用 catch 方法处理请求的错误。

这种实现方式使用了 Promise 来处理异步请求,并使用 setTimeout 来实现 5s 超时的效果,同时通过 then 和 catch 方法处理请求的响应结果或错误。这样就可以在请求未完成的情况下终止请求,并返回一个超时的错误,避免了程序的长时间等待。