小編給大家分享一下JavaScript如何實(shí)現(xiàn)指定數(shù)量的并發(fā)限制,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
成都創(chuàng)新互聯(lián)是專業(yè)的莊河網(wǎng)站建設(shè)公司,莊河接單;提供成都做網(wǎng)站、成都網(wǎng)站設(shè)計(jì),網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行莊河網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來合作!
在網(wǎng)上看到這么一道題:
這道題跟魚頭這篇記錄『什么是時(shí)間分片(Time Slicing)? 』有點(diǎn)相似,但不同的是這次是限制異步并發(fā)的數(shù)量。
所以話不多說,我們先來康康實(shí)現(xiàn)
首先我們來實(shí)現(xiàn)一個(gè)分割數(shù)組的函數(shù)~
const group = (list = [], max = 0) => { if (!list.length) { return list } let results = [] for (let i = 0, len = list.length; i < len; i += max) { results.push(list.slice(i, i + max)) } return results }
這里就是根據(jù)指定的并發(fā)數(shù)量來分割數(shù)組。主要就是 for
+ slice
,這沒啥好說的
接下來我們再來一個(gè)用 async
+ await
實(shí)現(xiàn)的請求集合封裝。
我們通過 for...of
去遍歷每一個(gè)異步函數(shù),然后用 async
+ await
確保函數(shù)的執(zhí)行順序,再用 try...catch
來保證即使 reject
報(bào)錯(cuò)也不會導(dǎo)致無法繼續(xù)執(zhí)行任務(wù)。
const requestHandler = async ( groupedUrl = [], callback = () => { } ) => { if (!groupedUrl.length) { callback() return groupedUrl } const newGroupedUrl = groupedUrl.map(fn => fn()) const resultsMapper = (results) => results.map(callback) const data = await Promise.allSettled(newGroupedUrl).then(resultsMapper) return data; }
接下來就是主函數(shù)
const sendRequest = async ( urls = [], max = 0, callback = () => { } ) => { if (!urls.length) { return urls } const groupedUrls = group(urls, max) const results = [] console.log('start !') for (let groupedUrl of groupedUrls) { try { const result = await requestHandler(groupedUrl, callback) results.push(result) console.log('go') } catch { } } console.log('done !') return results }
這里就是利用了 for
+ async
+ await
來限制并發(fā)。等每次并發(fā)任務(wù)結(jié)果出來之后再執(zhí)行下一次的任務(wù)。
我們執(zhí)行下栗子:
const p1 = () => new Promise((resolve, reject) => setTimeout(reject, 1000, 'p1')) const p2 = () => Promise.resolve(2) const p3 = () => new Promise((resolve, reject) => setTimeout(resolve, 2000, 'p3')) const p4 = () => Promise.resolve(4) const p5 = () => new Promise((resolve, reject) => setTimeout(reject, 2000, 'p5')) const p6 = () => Promise.resolve(6) const p7 = () => new Promise((resolve, reject) => setTimeout(resolve, 1000, 'p7')) const p8 = () => Promise.resolve(8) const p9 = () => new Promise((resolve, reject) => setTimeout(reject, 1000, 'p9')) const p10 = () => Promise.resolve(10) const p11 = () => new Promise((resolve, reject) => setTimeout(resolve, 2000, 'p10')) const p12 = () => Promise.resolve(12) const p13 = () => new Promise((resolve, reject) => setTimeout(reject, 1000, 'p11')) const p14 = () => Promise.resolve(14) const ps = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14] sendRequest(ps, 3, ({reason, value}) => { console.log(reason || value) })
OK,我們看到結(jié)果是如我們所愿的
看完了這篇文章,相信你對“JavaScript如何實(shí)現(xiàn)指定數(shù)量的并發(fā)限制”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!