Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

封装带有超时(重试)机制的异步请求工具函数 #177

Open
TieMuZhen opened this issue Apr 20, 2022 · 0 comments
Open

封装带有超时(重试)机制的异步请求工具函数 #177

TieMuZhen opened this issue Apr 20, 2022 · 0 comments

Comments

@TieMuZhen
Copy link
Owner

TieMuZhen commented Apr 20, 2022

//模拟请求逻辑
function asyncRequest(){
    return new Promise((resolve, reject) => {
        if(1){
            reject('reject');
        }else{
            resolve('resolve');
        }
    })
}

/**
 * 
 * @param {Promise} asyncRequest 需要重试的函数
 * @param {number} times 重试次数
 * @param {number} delay 多久后进行下一次重试
 * @returns {Promise}
 */
function reTry(asyncRequest, time, delay){
    return asyncRequest().catch(async err => {
        if(--time){
            await new Promise((resolve) => {
                setTimeout(resolve, delay);
            })
            return reTry(asyncRequest, time, delay);
        }else{
            throw '请求失败' + err;
        }
    })
}

reTry(asyncRequest, 3, 2000).then(value => {
    console.log(value + "成功");
}, err => {
    console.log(err + "失败");
})

输出

reject 3
reject 2
reject 1
请求失败reject失败
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant