问题描述
实现一个请求方法,支持自动重试,格式如下
function request(url, options, retry = 3) {
}
思路解析
通过递归实现,如果出现请求异常,则再次调用自己,通过Promise的链式调用即可
代码实现
function request(url, options, retry = 3) {
let count = 1;
const fetchWithRetry = () => {
return fetch(url, options).catch(err => {
if (count < retry) {
count++;
return fetchWithRetry();
} else {
throw err;
}
})
}
return fetchWithRetry();
}
测试用例
request('/api/xxx').then(console.log);