JavaScript/TypeScript 實現并發請求控制的示例代碼
假設有 10 個請求,但是最大的并發數目是 5 個,并且要求拿到請求結果,這樣就是一個簡單的并發請求控制
模擬利用 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);
通過這樣來模擬請求,本質就是 Promise
沒有并發控制的時候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 的時間輸出了
并發條件假設同時間最大并發數目是 2,創建一個類
class Concurrent { private maxConcurrent: number = 2; constructor(count: number = 2) { this.maxConcurrent = count; }}第一種并發控制
想一下,按最大并發數拆分 Promise 數組,如果有 Promise 被 fulfilled 的時候,就移除掉,然后把 pending 狀態的 Promise ,加進來。Promise.race 可以幫我們滿足這個需求
class Concurrent { private maxConcurrent: number = 2; constructor(count: number = 2) { this.maxConcurrent = count; } public async useRace(fns: Function[]) { const runing: any[] = []; // 按并發數,把 Promise 加進去 // Promise 會回調一個索引,方便我們知道哪個 Promise 已經 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()!; // 移除已經完成的 Promise,把新的進去 runing.splice(idx, 1, nextFn(idx)); handle(); } else { // 如果數組已經被清空了,表面已經沒有需要執行的 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
可以看到輸出已經變了,為什么會這樣呢,分析一下,最大并發數 2
// 首先執行的是 1 21 需要 1000 MS 才執行完2 需要 300 MS
2 執行完,時間線變成 300 移除 2 加入 3 開始執行 33 需要 400MS 執行完時間變成 700 移除 3 加入 4 開始執行 44 需要 500MS時間線來到 1000MS,1 執行完 移除 1 加入 5 開始執行 5時間線來到 1200MS,4 和 5 剛好同時執行完
第二種方案可以利用 await 的機制,其實也是一個小技巧
await 表達式會暫停當前 async function 的執行,等待 Promise 處理完成。若 Promise 正常處理(fulfilled),其回調的 resolve 函數參數作為 await 表達式的值,繼續執行 async function。
如果當前的并發數已經超過最大的并發數目了,可以設置一個新的 Promise,并且 await,等待其他的請求完成的時候,resolve,移除等待,所以需要新增兩個狀態,當前的并發數目,還有用來存儲 resolve 這個回調函數的數組
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; // 如果最大已經超過最大并發數 if (this.currentCount > this.maxConcurrent) { // wait 是一個 Promise,只要調用 resolve 就會變成 fulfilled 狀態 const wait = new Promise((resolve) => { this.list.push(resolve); }); // 在沒有調用 resolve 的時候,這里會一直阻塞 await wait; } // 執行函數 await fn(); this.currentCount -= 1; if (this.list.length) { // 把 resolve 拿出來,調用,這樣 wait 就完成了,可以往下面執行了 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總結
這兩種方式都可以實現并發控制,只不過實現的方式不太一樣,主要都是靠 Promise 實現,另外實現方式里面沒有考慮異常的情況,這個可以自己加上
到此這篇關于JavaScript/TypeScript 實現并發請求控制的示例代碼的文章就介紹到這了,更多相關JavaScript 并發請求控制內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
