日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

如何限制請求的并發數量

作者:大橘為重¨ 更新時間: 2023-07-14 編程語言

如何限制請求的并發數量

  • 設計思路:
  • 代碼實現:


需求:當前端同時發出多個api請求,在前端對請求的并發數量進行限制,做到同時只能處理有限個請求任務

設計思路:

  • 設計 Scheduler 類 對需要發送的請求進行同一管理
  • 類中配置最大并發數 “max”,并記錄正在執行的請求數目 “count”
  • 通過 await + Promise 對超出限制數量時的請求進行阻塞
  • 當正在執行的請求完成后,按順序對阻塞的請求進行放行

代碼實現:

模擬請求

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類實現:

class Scheduler {
    constructor(max) {
        this.max = max    // 記錄支持并發的任務數量
        this.count = 0    // 當前正在執行的任務數
        this.stack = []   // 使用隊列保存被阻塞任務
    }

    async add(fun) {
        // 當正在執行的任務個數大于最大并發數時:使用await阻塞該請求的發送,記錄 reslove 到 stack 下   
        // 待執行中的任務完成后按順序對 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
    }
}

效果測試:

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

提示:文章到此結束,文章為個人學習記錄,侵刪。

原文鏈接:https://blog.csdn.net/weixin_53068161/article/details/131629134

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新