--061fd5245b500221 x-next-cache-tags: _N_T_/layout,_N_T_/blog/layout,_N_T_/blog/[...slug]/layout,_N_T_/blog/[...slug]/page,_N_T_/blog/%E6%89%8B%E5%86%99%E7%B3%BB%E5%88%97/%E5%9F%BA%E4%BA%8Epromise%E7%9A%84%E8%AF%B7%E6%B1%82%E9%87%8D%E8%AF%95 vary: RSC, Next-Router-State-Tree, Next-Router-Prefetch 基于promise的请求重试 | YBinary
Published on

基于promise的请求重试

Authors

背景 实现一个函数 实现一个重试功能,当异步任务失败时,等待N秒后会自动重试直到成功或达到最大重试次数。

const query = () => {
    return fetch(
        'https://api.juejin.cn/user_api/v1/user/dynamic?user_id=3649990025815853&cursor=0&aid=2608&uuid=7387740407814587904&spider=0',
    );
};

const retryPromise = (task,count,time) => {

  return   new Promise((resolve,reject) => {

            let count_run = 0;
            const run = () => {
            
                task()
                .then((data) => {
                    resolve(data)
                })
                .catch(e => {  
                     count_run++;
                    if(count_run <= count) {
                        setTimeout(run,time)
                    }else {
                        reject(e)
                    }
                    
                })

            }

        })

}


--061fd5245b500221--