Daily question: Encapsulate a request function, requiring automatic retries at most n times, and returning the result directly after any successful request.

Daily question

Please encapsulate a request function, requiring automatic retries at most n times, and returning the result directly after any successful request.

  • Simple version
async function requestWithRetry(url, maxRetries) {
    
    
      let retries = 0;
      let lastError = null;

      while (retries < maxRetries) {
    
    
        try {
    
    
          const response = await fetch(url);
          const data = await response.json();
          return data;
        } catch (error) {
    
    
          lastError = error;
          retries++;
        }
      }

      throw lastError; 
    }

To ensure some robustness, let's make some supplementary capabilities.

  • The following is a simple JavaScript request function with automatic retry function. The function uses the fetch API, and you can replace it with other request libraries as needed.
async function retryableFetch(url, maxRetries = 3) {
    
    
  let retries = 0;

  while (retries < maxRetries) {
    
    
    try {
    
    
      const response = await fetch(url);
      if (response.ok) {
    
    
        return response.json(); // 返回 JSON 数据,你可以根据需要调整
      }
    } catch (error) {
    
    
      console.error(`Request failed, retrying (${
      
      retries + 1}/${
      
      maxRetries})`, error);
    }

    retries++;
  }

  throw new Error(`Failed to fetch after ${
      
      maxRetries} retries`);
}

// 使用示例
const url = 'https://jsonplaceholder.typicode.com/todos/1';
retryableFetch(url)
  .then(data => console.log(data))
  .catch(error => console.error(error));

This function will retry when the request fails, up to maxRetries times. If the request is successful, it parses the JSON data and returns it, otherwise it throws an error after the maximum number of retries is reached.

Please note that this is just a basic example, and in actual scenarios you may need to make more customizations based on your needs. In addition, some edge cases must be considered, such as request timeouts, network errors, etc.

Guess you like

Origin blog.csdn.net/m0_46672781/article/details/134827375