最近看到有人在写失败重试的方法,我也顺手写一个,代码非常简单。
show code
function fetchWithRetry(url, retries = 3) {
return fetch(url).then(res => Promise.resolve(res), err => retries > 0 ? fetchWithRetry(url, retries - 1) : Promise.reject(err))
}
fetchWithRetry('https://example.com/api')
发起一个请求,如果成功直接返回,如果失败,则会最多再重试三次。
nice~