Skip to content

并发处理异步请求 #98

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

Open
Twlig opened this issue Apr 19, 2022 · 0 comments
Open

并发处理异步请求 #98

Twlig opened this issue Apr 19, 2022 · 0 comments

Comments

@Twlig
Copy link
Owner

Twlig commented Apr 19, 2022

处理并发请求,并且要求最大并发数量是10

// 模拟一百条数据 
const message = new Array(100).fill(''); 
for (let i = 0; i < 100; i++) {  message[i] = '第' + i + '条数据'; } // 模拟请求一千条数据
//模拟异步请求出现部分错误
function getAxiosMessage(idx) {  
    return new Promise((resolve, reject) => {
        setTimeout(()=>{
            if(idx % 7 == 1) {
                reject('错误' + idx)
            } else {
                resolve(message[idx])
            }
        }, 1000)
    })
}
//异步获取消息
/*
	1. 用race来保证并发任务队列的大小
	2. 考虑出现reject情况下,对错误进行收集
*/
async function getAsyncMessage(max = 10) {
    var task = []
    var ans = []
    var errArr = []
    for(let i = 0; i < 100; i++) {
        const p = getAxiosMessage(i).then(res => {
            ans.push(res)
            task.splice(task.indexOf(p), 1)
        },err => {
            //假如发生超时等,加入reject数组,或者是重新执行
            console.log('错误' + i)
            errArr.push(err)
            task.splice(task.indexOf(p), 1)
        })
        task.push(p)
        if(task.length == max) {
            await Promise.race(task)
        }
    }
    await Promise.allSettled(task)
    return [ans, errArr]
}
getAsyncMessage().then(res=>{
    console.log(res[0])
    console.log(res[1])
})
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