Skip to content

实现一个请求函数:fetchWithRetry,要求会最多自动重试 3 次,任意一次成功就直接返回

Posted on:2023年7月8日 at 15:54

下面是一个简单的示例实现,并未包含对异常情况的处理、超时设置等较复杂的功能:

function fetchWithRetry(url, options, maxRetry = 3) {
  return new Promise((resolve, reject) => {
    const doFetch = async (attempt) => {
      try {
        const response = await fetch(url, options);
        if (response.ok) {
          resolve(response);
        } else {
          throw new Error("Request failed");
        }
      } catch (error) {
        if (attempt < maxRetry) {
          console.log(`Attempt ${attempt + 1} failed. Retrying...`);
          doFetch(attempt + 1);
        } else {
          reject(new Error("Max retries exceeded"));
        }
      }
    };

    doFetch(0);
  });
}
原文转自:https://fe.ecool.fun/topic/be0412b7-6af9-4ab5-9c7f-4a06cc8cc80d