JavaScript/TypeScript 實(shí)現(xiàn)并發(fā)請(qǐng)求控制的示例代碼
場(chǎ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);
通過這樣來模擬請(qǐng)求,本質(zhì)就是 Promise
沒有并發(fā)控制的時(shí)候
const run = async () => { startTime = Date.now(); await Promise.all([ timeout1(), timeout2(), timeout3(), timeout4(), timeout5(), ]); }; run(); At 200 return 5 At 300 return 2 At 400 return 3 At 500 return 4 At 1000 return 1
可以看到輸出是 5 2 3 4 1 ,按 timeout 的時(shí)間輸出了
并發(fā)條件
假設(shè)同時(shí)間最大并發(fā)數(shù)目是 2,創(chuàng)建一個(gè)類
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)來。Promise.race 可以幫我們滿足這個(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)沒有需要執(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 2 At 700 return 3 At 1000 return 1 At 1200 return 5 At 1200 return 4
可以看到輸出已經(jīng)變了,為什么會(huì)這樣呢,分析一下,最大并發(fā)數(shù) 2
// 首先執(zhí)行的是 1 2
1 需要 1000 MS 才執(zhí)行完
2 需要 300 MS2 執(zhí)行完,時(shí)間線變成 300 移除 2 加入 3 開始執(zhí)行 3
3 需要 400MS 執(zhí)行完時(shí)間變成 700 移除 3 加入 4 開始執(zhí)行 4
4 需要 500MS
時(shí)間線來到 1000MS,1 執(zhí)行完 移除 1 加入 5 開始執(zhí)行 5
時(shí)間線來到 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)超過最大的并發(fā)數(shù)目了,可以設(shè)置一個(gè)新的 Promise,并且 await,等待其他的請(qǐng)求完成的時(shí)候,resolve,移除等待,所以需要新增兩個(gè)狀態(tài),當(dāng)前的并發(fā)數(shù)目,還有用來存儲(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)超過最大并發(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); }); // 在沒有調(diào)用 resolve 的時(shí)候,這里會(huì)一直阻塞 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 2 At 700 return 3 At 1000 return 1 At 1200 return 5 At 1200 return 4
總結(jié)
這兩種方式都可以實(shí)現(xiàn)并發(fā)控制,只不過實(shí)現(xiàn)的方式不太一樣,主要都是靠 Promise 實(shí)現(xiàn),另外實(shí)現(xiàn)方式里面沒有考慮異常的情況,這個(gè)可以自己加上
到此這篇關(guān)于JavaScript/TypeScript 實(shí)現(xiàn)并發(fā)請(qǐng)求控制的示例代碼的文章就介紹到這了,更多相關(guān)JavaScript 并發(fā)請(qǐng)求控制內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript無(wú)操作后屏保功能的實(shí)現(xiàn)方法
今天組里的同事要寫一個(gè)屏保的效果,要求鼠標(biāo)無(wú)操作N秒后進(jìn)入屏幕保護(hù),滑動(dòng)鼠標(biāo)的時(shí)候取消屏幕保護(hù)。我真是難倒了,糾結(jié)了半天,搞定了,下面給大家分享實(shí)現(xiàn)代碼2017-07-07js實(shí)現(xiàn)導(dǎo)航欄中英文切換效果
本篇文章主要分享了javascript實(shí)現(xiàn)導(dǎo)航欄中英文切換效果的示例代碼,具有很好的參考價(jià)值,下面跟著小編一起來看下吧2017-01-016種JavaScript繼承方式及優(yōu)缺點(diǎn)(小結(jié))
這篇文章主要介紹了6種JavaScript繼承方式及優(yōu)缺點(diǎn)(小結(jié)),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02js實(shí)現(xiàn)tab選項(xiàng)卡函數(shù)代碼
js實(shí)現(xiàn)tab選項(xiàng)卡函數(shù)代碼,需要的朋友可以參考下,這樣的代碼也是比較常用的,相當(dāng)原理也比較簡(jiǎn)單。2010-04-04js實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)的五種方法推薦
下面小編就為大家?guī)硪黄猨s實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)的五種方法推薦。小編覺得挺不錯(cuò)的?,F(xiàn)在分享給大家。給大家參考一下。2016-03-03JS實(shí)現(xiàn)調(diào)用本地?cái)z像頭功能示例
這篇文章主要介紹了JS實(shí)現(xiàn)調(diào)用本地?cái)z像頭功能,結(jié)合實(shí)例形式分析了Javascript基于瀏覽器對(duì)本地硬件操作簡(jiǎn)單實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-05-05微信小程序開發(fā)之視頻播放器 Video 彈幕 彈幕顏色自定義實(shí)例
本篇文章主要介紹了微信小程序開發(fā)之視頻播放器 Video 彈幕 彈幕顏色自定義實(shí)例,具有一定的參考價(jià)值,有興趣的同學(xué)可以了解一下。2016-12-12支付寶小程序?qū)崿F(xiàn)省市區(qū)三級(jí)聯(lián)動(dòng)
這篇文章主要為大家詳細(xì)介紹了支付寶小程序?qū)崿F(xiàn)省市區(qū)三級(jí)聯(lián)動(dòng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06微信小程序bindinput與bindsubmit的區(qū)別實(shí)例分析
這篇文章主要介紹了微信小程序bindinput與bindsubmit的區(qū)別,結(jié)合實(shí)例形式分析了微信小程序bindinput與bindsubmit的具體功能、用法及相關(guān)使用區(qū)別,需要的朋友可以參考下2019-04-04