JavaScript/TypeScript 實(shí)現(xiàn)并發(fā)請(qǐng)求控制的示例代碼
假設(shè)有 10 個(gè)請(qǐng)求,但是最大的并發(fā)數(shù)目是 5 個(gè),并且要求拿到請(qǐng)求結(jié)果,這樣就是一個(gè)簡(jiǎn)單的并發(fā)請(qǐng)求控制
模擬利用 setTimeout 實(shí)行簡(jiǎn)單模仿一個(gè)請(qǐng)求
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);
通過(guò)這樣來(lái)模擬請(qǐng)求,本質(zhì)就是 Promise
沒(méi)有并發(fā)控制的時(shí)候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 的時(shí)間輸出了
并發(fā)條件假設(shè)同時(shí)間最大并發(fā)數(shù)目是 2,創(chuàng)建一個(gè)類(lèi)
class Concurrent { private maxConcurrent: number = 2; constructor(count: number = 2) { this.maxConcurrent = count; }}第一種并發(fā)控制
想一下,按最大并發(fā)數(shù)拆分 Promise 數(shù)組,如果有 Promise 被 fulfilled 的時(shí)候,就移除掉,然后把 pending 狀態(tài)的 Promise ,加進(jìn)來(lái)。Promise.race 可以幫我們滿(mǎn)足這個(gè)需求
class Concurrent { private maxConcurrent: number = 2; constructor(count: number = 2) { this.maxConcurrent = count; } public async useRace(fns: Function[]) { const runing: any[] = []; // 按并發(fā)數(shù),把 Promise 加進(jìn)去 // Promise 會(huì)回調(diào)一個(gè)索引,方便我們知道哪個(gè) 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,把新的進(jìn)去 runing.splice(idx, 1, nextFn(idx)); handle(); } else { // 如果數(shù)組已經(jīng)被清空了,表面已經(jīng)沒(méi)有需要執(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)變了,為什么會(huì)這樣呢,分析一下,最大并發(fā)數(shù) 2
// 首先執(zhí)行的是 1 21 需要 1000 MS 才執(zhí)行完2 需要 300 MS
2 執(zhí)行完,時(shí)間線(xiàn)變成 300 移除 2 加入 3 開(kāi)始執(zhí)行 33 需要 400MS 執(zhí)行完時(shí)間變成 700 移除 3 加入 4 開(kāi)始執(zhí)行 44 需要 500MS時(shí)間線(xiàn)來(lái)到 1000MS,1 執(zhí)行完 移除 1 加入 5 開(kāi)始執(zhí)行 5時(shí)間線(xiàn)來(lái)到 1200MS,4 和 5 剛好同時(shí)執(zhí)行完
第二種方案可以利用 await 的機(jī)制,其實(shí)也是一個(gè)小技巧
await 表達(dá)式會(huì)暫停當(dāng)前 async function 的執(zhí)行,等待 Promise 處理完成。若 Promise 正常處理(fulfilled),其回調(diào)的 resolve 函數(shù)參數(shù)作為 await 表達(dá)式的值,繼續(xù)執(zhí)行 async function。
如果當(dāng)前的并發(fā)數(shù)已經(jīng)超過(guò)最大的并發(fā)數(shù)目了,可以設(shè)置一個(gè)新的 Promise,并且 await,等待其他的請(qǐng)求完成的時(shí)候,resolve,移除等待,所以需要新增兩個(gè)狀態(tài),當(dāng)前的并發(fā)數(shù)目,還有用來(lái)存儲(chǔ) resolve 這個(gè)回調(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)超過(guò)最大并發(fā)數(shù) if (this.currentCount > this.maxConcurrent) { // wait 是一個(gè) Promise,只要調(diào)用 resolve 就會(huì)變成 fulfilled 狀態(tài) const wait = new Promise((resolve) => { this.list.push(resolve); }); // 在沒(méi)有調(diào)用 resolve 的時(shí)候,這里會(huì)一直阻塞 await wait; } // 執(zhí)行函數(shù) await fn(); this.currentCount -= 1; if (this.list.length) { // 把 resolve 拿出來(lái),調(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é)
這兩種方式都可以實(shí)現(xiàn)并發(fā)控制,只不過(guò)實(shí)現(xiàn)的方式不太一樣,主要都是靠 Promise 實(shí)現(xiàn),另外實(shí)現(xiàn)方式里面沒(méi)有考慮異常的情況,這個(gè)可以自己加上
到此這篇關(guān)于JavaScript/TypeScript 實(shí)現(xiàn)并發(fā)請(qǐng)求控制的示例代碼的文章就介紹到這了,更多相關(guān)JavaScript 并發(fā)請(qǐng)求控制內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向2. Nginx+php配置文件及原理解析3. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼4. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題5. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析6. 淺談python出錯(cuò)時(shí)traceback的解讀7. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法8. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解9. Ajax實(shí)現(xiàn)表格中信息不刷新頁(yè)面進(jìn)行更新數(shù)據(jù)10. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法
