+
95
-

回答

要在JavaScript中为fetch请求增加重试次数,您可以使用递归函数来处理请求,以便在失败时进行多次重试。以下是一个示例,展示了如何实现这个功能:

function fetchWithRetry(url, maxRetries, retryInterval) {
  return fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response;
    })
    .catch(error => {
      if (maxRetries > 0) {
        console.error(`Request failed. Retrying in ${retryInterval}ms...`);
        return new Promise(resolve => {
          setTimeout(() => {
            console.log(`Retrying... (${maxRetries} retries left)`);
            resolve(fetchWithRetry(url, maxRetries - 1, retryInterval));
          }, retryInterval);
        });
      } else {
        throw error;
      }
    });
}

// 使用示例:
const url = 'https://example.com/api/data';
const maxRetries = 3; // 设置重试次数
const retryInterval = 1000; // 重试间隔(毫秒)

fetchWithRetry(url, maxRetries, retryInterval)
  .then(response => {
    // 在这里处理成功的响应
    console.log('Success:', response);
  })
  .catch(error => {
    // 在这里处理所有重试后仍然失败的情况
    console.error('Request failed after retries:', error);
  });

上述代码中,fetchWithRetry 函数会尝试执行fetch请求,并在请求失败时重试,最多重试指定的次数。如果所有重试都失败,它会将错误抛出以供处理。

请注意,重试请求需要谨慎使用,以避免对目标服务器施加不必要的负担。在实际使用中,您可以根据您的需求来设置合适的重试次数和重试间隔。

网友回复

我知道答案,我要回答