JavaScript/TypeScript 實現(xiàn)并發(fā)請求控制的示例代碼
假設(shè)有 10 個請求,但是最大的并發(fā)數(shù)目是 5 個,并且要求拿到請求結(jié)果,這樣就是一個簡單的并發(fā)請求控制
模擬利用 setTimeout 實行簡單模仿一個請求
let startTime = Date.now();const timeout = (timeout: number, ret: number) => { return (idx?: any) => new Promise((resolve) => { setTimeout(() => { const compare = Date.now() - startTime; console.log(`At ${Math.floor(compare / 100)}00 return`, ret); resolve(idx); }, timeout); });};const timeout1 = timeout(1000, 1);const timeout2 = timeout(300, 2);const timeout3 = timeout(400, 3);const timeout4 = timeout(500, 4);const timeout5 = timeout(200, 5);
通過這樣來模擬請求,本質(zhì)就是 Promise
沒有并發(fā)控制的時候const run = async () => { startTime = Date.now(); await Promise.all([ timeout1(), timeout2(), timeout3(), timeout4(), timeout5(), ]);};run();At 200 return 5At 300 return 2At 400 return 3At 500 return 4At 1000 return 1
可以看到輸出是 5 2 3 4 1 ,按 timeout 的時間輸出了
并發(fā)條件假設(shè)同時間最大并發(fā)數(shù)目是 2,創(chuàng)建一個類
class Concurrent { private maxConcurrent: number = 2; constructor(count: number = 2) { this.maxConcurrent = count; }}第一種并發(fā)控制
想一下,按最大并發(fā)數(shù)拆分 Promise 數(shù)組,如果有 Promise 被 fulfilled 的時候,就移除掉,然后把 pending 狀態(tài)的 Promise ,加進來。Promise.race 可以幫我們滿足這個需求
class Concurrent { private maxConcurrent: number = 2; constructor(count: number = 2) { this.maxConcurrent = count; } public async useRace(fns: Function[]) { const runing: any[] = []; // 按并發(fā)數(shù),把 Promise 加進去 // Promise 會回調(diào)一個索引,方便我們知道哪個 Promise 已經(jīng) resolve 了 for (let i = 0; i < this.maxConcurrent; i++) { if (fns.length) { const fn = fns.shift()!; runing.push(fn(i)); } } const handle = async () => { if (fns.length) { const idx = await Promise.race<number>(runing); const nextFn = fns.shift()!; // 移除已經(jīng)完成的 Promise,把新的進去 runing.splice(idx, 1, nextFn(idx)); handle(); } else { // 如果數(shù)組已經(jīng)被清空了,表面已經(jīng)沒有需要執(zhí)行的 Promise 了,可以改成 Promise.all await Promise.all(runing); } }; handle(); }}const run = async () => { const concurrent = new Concurrent(); startTime = Date.now(); await concurrent.useRace([timeout1, timeout2, timeout3, timeout4, timeout5]);};At 300 return 2At 700 return 3At 1000 return 1At 1200 return 5At 1200 return 4
可以看到輸出已經(jīng)變了,為什么會這樣呢,分析一下,最大并發(fā)數(shù) 2
// 首先執(zhí)行的是 1 21 需要 1000 MS 才執(zhí)行完2 需要 300 MS
2 執(zhí)行完,時間線變成 300 移除 2 加入 3 開始執(zhí)行 33 需要 400MS 執(zhí)行完時間變成 700 移除 3 加入 4 開始執(zhí)行 44 需要 500MS時間線來到 1000MS,1 執(zhí)行完 移除 1 加入 5 開始執(zhí)行 5時間線來到 1200MS,4 和 5 剛好同時執(zhí)行完
第二種方案可以利用 await 的機制,其實也是一個小技巧
await 表達式會暫停當(dāng)前 async function 的執(zhí)行,等待 Promise 處理完成。若 Promise 正常處理(fulfilled),其回調(diào)的 resolve 函數(shù)參數(shù)作為 await 表達式的值,繼續(xù)執(zhí)行 async function。
如果當(dāng)前的并發(fā)數(shù)已經(jīng)超過最大的并發(fā)數(shù)目了,可以設(shè)置一個新的 Promise,并且 await,等待其他的請求完成的時候,resolve,移除等待,所以需要新增兩個狀態(tài),當(dāng)前的并發(fā)數(shù)目,還有用來存儲 resolve 這個回調(diào)函數(shù)的數(shù)組
class Concurrent { private maxConcurrent: number = 2; private list: Function[] = []; private currentCount: number = 0; constructor(count: number = 2) { this.maxConcurrent = count; } public async add(fn: Function) { this.currentCount += 1; // 如果最大已經(jīng)超過最大并發(fā)數(shù) if (this.currentCount > this.maxConcurrent) { // wait 是一個 Promise,只要調(diào)用 resolve 就會變成 fulfilled 狀態(tài) const wait = new Promise((resolve) => { this.list.push(resolve); }); // 在沒有調(diào)用 resolve 的時候,這里會一直阻塞 await wait; } // 執(zhí)行函數(shù) await fn(); this.currentCount -= 1; if (this.list.length) { // 把 resolve 拿出來,調(diào)用,這樣 wait 就完成了,可以往下面執(zhí)行了 const resolveHandler = this.list.shift()!; resolveHandler(); } }}const run = async () => { const concurrent = new Concurrent(); startTime = Date.now(); concurrent.add(timeout1); concurrent.add(timeout2); concurrent.add(timeout3); concurrent.add(timeout4); concurrent.add(timeout5);};run();At 300 return 2At 700 return 3At 1000 return 1At 1200 return 5At 1200 return 4總結(jié)
這兩種方式都可以實現(xiàn)并發(fā)控制,只不過實現(xiàn)的方式不太一樣,主要都是靠 Promise 實現(xiàn),另外實現(xiàn)方式里面沒有考慮異常的情況,這個可以自己加上
到此這篇關(guān)于JavaScript/TypeScript 實現(xiàn)并發(fā)請求控制的示例代碼的文章就介紹到這了,更多相關(guān)JavaScript 并發(fā)請求控制內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題2. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)3. 如何在jsp界面中插入圖片4. 爬取今日頭條Ajax請求5. jsp EL表達式詳解6. Ajax實現(xiàn)表格中信息不刷新頁面進行更新數(shù)據(jù)7. jsp中sitemesh修改tagRule技術(shù)分享8. asp(vbscript)中自定義函數(shù)的默認(rèn)參數(shù)實現(xiàn)代碼9. ASP基礎(chǔ)知識VBScript基本元素講解10. JSP servlet實現(xiàn)文件上傳下載和刪除
