Skip to content

实现请求重试

实现一个简单的请求重试函数,当请求失败时,会自动重试指定次数。

代码展示
js
const promiseRetry = (url, options = {}, maxRetryTimes = 3) => {
    return new Promise((resolve, reject) => {
        const doFetch = async (count) => {
            try {
                const res = await fetch(url, options)
                if (res.ok) {
                    resolve(res)
                } else {
                    throw new Error('请求失败')
                }
            } catch (error) {
                if (count < maxRetryTimes) {
                    console.log(`请求失败,进行第${count + 1}次重试`)
                    doFetch(count + 1)
                } else {
                    reject(new Error('请求重试次数超过最大次数'))
                }
            }
        }
        doFetch(0)
    })
}

使用示例:

js
promiseRetry('/api/data', { method: 'GET' })
    .then(res => console.log(res))
    .catch(err => console.error(err))