Skip to content

封装自动重试的fetch

🕒 Published at:
js
function fetchRetry(url, data) {
  const request = async (maxCount) => {
    let response
    try {
      // 请求成功,但后端报错
      response = await fetch(url, { method: 'POST', data })
      if (response.status !== 200 && maxCount > 0) {
        // console.log('maxCount: ', maxCount)
        response = retry(maxCount)
      }
    } catch (e) {
      // 请求失败的情况
      if (maxCount > 0) {
        response = retry(maxCount)
      } else {
        response = e
      }
    }
    return response
  }

  const retry = (maxCount) => {
    // console.log('maxCount: ', maxCount)
    return request(maxCount - 1)
  }

  return request(5)
}

// fetch报错失败重试的测试
// fetchRetry('http://localhost:8084', 5).then((resonse) => {
//   // console.log(resonse)
// })

// 特定状态码(测试不是200)报错的情况重试
fetchRetry('http://localhost:8083', 5).then(res => res.json()).then((data) => {
  console.log(data)
})

// 成功的测试
// fetchRetry('http://localhost:8083', 5)

参考fetch-retry

简单的测试服务器

js
import http from 'http'
const server = http.createServer((resquest, response) => {
  console.log('incoming...')
  const code = 500
  let data = JSON.stringify({ code, message: "success" })
  response.statusCode = code
  response.appendHeader('Access-Control-Allow-Origin', "*")
  response.write(data);
  response.end();
});
const port = '8083';
server.listen(port, () => {
  console.log(`http://localhost:${port}`);
})