promise实现请求重试原创

原创
小哥 5个月前 (02-08) 阅读数 48 #大杂烩

使用promise实现请求重试:请求失败延迟n秒后重新发送请求,重试次数达到最大。

// getData 请求函数
// times 最大重试次数
// delay 重试延迟时间
function retry(getData, times, delay) {
    return new Promise((resolve, reject) => {
        function attempt() {
            getData.then(resolve).catch((err) => {
                console.log(还有${times}次机会)
                if(times == 0) {
                    reject(err)
                } else {
                    times--
                    setTimeout(attempt(), delay)
                }
            })
        }
        attempt()
    })
}
版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除