需求:當前端同時發(fā)出多個api請求,在前端對請求的并發(fā)數(shù)量進行限制,做到同時只能處理有限個請求任務
設計思路:
- 設計 Scheduler 類 對需要發(fā)送的請求進行統(tǒng)一管理
- 類中配置最大并發(fā)數(shù) “max”,并記錄正在執(zhí)行的請求數(shù)目 “count”
- 通過 await + Promise 對超出限制數(shù)量時的請求進行阻塞
- 當正在執(zhí)行的請求完成后,按順序?qū)ψ枞恼埱筮M行放行
代碼實現(xiàn):
模擬請求
function sleep(val, time) {
return new Promise(reslove => {
setTimeout(() => {
reslove(val)
}, time)
})
}
function addTask(val, time) {
return () => sleep(val, time).then(result => {
console.log(result);
return result
})
}
Scheduler類實現(xiàn):文章來源:http://www.zghlxwxcb.cn/news/detail-541589.html
class Scheduler {
constructor(max) {
this.max = max // 記錄支持并發(fā)的任務數(shù)量
this.count = 0 // 當前正在執(zhí)行的任務數(shù)
this.stack = [] // 使用隊列保存被阻塞任務
}
async add(fun) {
// 當正在執(zhí)行的任務個數(shù)大于最大并發(fā)數(shù)時:使用await阻塞該請求的發(fā)送,記錄 reslove 到 stack 下
// 待執(zhí)行中的任務完成后按順序?qū)?stack 中的阻塞任務放行
if (this.count >= this.max) {
await new Promise(reslove => this.stack.push(reslove))
}
this.count = this.count + 1
let result = await fun()
this.count = this.count - 1
if (this.stack.length) this.stack.shift()()
return result
}
}
效果測試:文章來源地址http://www.zghlxwxcb.cn/news/detail-541589.html
const scheduler = new Scheduler(2)
scheduler.add(addTask(1, 1000))
scheduler.add(addTask(2, 500))
scheduler.add(addTask(3, 400))
scheduler.add(addTask(4, 200))
// 打印 2 3 1 4
提示:文章到此結(jié)束,文章為個人學習記錄,侵刪。
到了這里,關(guān)于如何限制請求的并發(fā)數(shù)量的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!