JavaScript異步操作中串行和并行
1、前言
本文寫(xiě)一下js
中es5
和es6
針對(duì)異步函數(shù),串行執(zhí)行和并行執(zhí)行的方案。已經(jīng)串行和并行結(jié)合使用的例子。
2、es5方式
在es6出來(lái)之前,社區(qū)nodejs
中針對(duì)回調(diào)地獄,已經(jīng)有了promise
方案。假如多個(gè)異步函數(shù),執(zhí)行循序怎么安排,如何才能更快的執(zhí)行完所有異步函數(shù),再執(zhí)行下一步呢?這里就出現(xiàn)了js的串行執(zhí)行和并行執(zhí)行問(wèn)題。
3、異步函數(shù)串行執(zhí)行
var items = [ 1, 2, 3, 4, 5, 6 ]; var results = []; function async(arg, callback) { console.log('參數(shù)為 ' + arg +' , 1秒后返回結(jié)果'); setTimeout(function () { callback(arg * 2); }, 1000); } function final(value) { console.log('完成: ', value); } function series(item) { if(item) { async( item, function(result) { results.push(result); return series(items.shift());// 遞歸執(zhí)行完所有的數(shù)據(jù) }); } else { return final(results[results.length - 1]); } } series(items.shift());
4、異步函數(shù)并行執(zhí)行
上面函數(shù)是一個(gè)一個(gè)執(zhí)行的,上一個(gè)執(zhí)行結(jié)束再執(zhí)行下一個(gè),類(lèi)似es6
(es5之后統(tǒng)稱(chēng)es6)中 async 和await,那有沒(méi)有類(lèi)似promise.all
這種,所有的并行執(zhí)行的呢?
可以如下寫(xiě):
var items = [ 1, 2, 3, 4, 5, 6 ]; var results = []; function async(arg, callback) { console.log('參數(shù)為 ' + arg +' , 1秒后返回結(jié)果'); setTimeout(function () { callback(arg * 2); }, 1000); } function final(value) { console.log('完成: ', value); } items.forEach(function(item) {// 循環(huán)完成 async(item, function(result){ results.push(result); if(results.length === items.length) {// 判斷執(zhí)行完畢的個(gè)數(shù)是否等于要執(zhí)行函數(shù)的個(gè)數(shù) final(results[results.length - 1]); } }) });
5、異步函數(shù)串行執(zhí)行和并行執(zhí)行結(jié)合
假如并行執(zhí)行很多條異步(幾百條)數(shù)據(jù),每個(gè)異步數(shù)據(jù)中有很多的(https)請(qǐng)求數(shù)據(jù),勢(shì)必造成tcp 連接數(shù)不足,或者堆積了無(wú)數(shù)調(diào)用棧導(dǎo)致內(nèi)存溢出。所以并行執(zhí)行不易太多數(shù)據(jù),因此,出現(xiàn)了并行和串行結(jié)合的方式。
代碼可以如下書(shū)寫(xiě):
var items = [ 1, 2, 3, 4, 5, 6 ]; var results = []; var running = 0; var limit = 2; function async(arg, callback) { console.log('參數(shù)為 ' + arg +' , 1秒后返回結(jié)果'); setTimeout(function () { callback(arg * 2); }, 1000); } function final(value) { console.log('完成: ', value); } function launcher() { while(running < limit && items.length > 0) { var item = items.shift(); async(item, function(result) { results.push(result); running--; if(items.length > 0) { launcher(); } else if(running == 0) { final(results); } }); running++; } } launcher();
6、es6方式
es6
天然自帶串行和并行的執(zhí)行方式,例如串行可以用async
和await
(前文已經(jīng)講解),并行可以用promise.all等等。那么針對(duì)串行和并行結(jié)合,限制promise all
并發(fā)數(shù)量,社區(qū)也有一些方案,例如
tiny-async-pool、es6-promise-pool、p-limit
簡(jiǎn)單封裝一個(gè)promise all
并發(fā)數(shù)限制解決方案函數(shù)
function PromiseLimit(funcArray, limit = 5) { // 并發(fā)執(zhí)行5條數(shù)據(jù) let i = 0; const result = []; const executing = []; const queue = function() { if (i === funcArray.length) return Promise.all(executing); const p = funcArray[i++](); result.push(p); const e = p.then(() => executing.splice(executing.indexOf(e), 1)); executing.push(e); if (executing.length >= limit) { return Promise.race(executing).then( () => queue(), e => Promise.reject(e) ); } return Promise.resolve().then(() => queue()); }; return queue().then(() => Promise.all(result)); }
使用:
// 測(cè)試代碼 const result = []; for (let index = 0; index < 10; index++) { result.push(function() { return new Promise((resolve, reject) => { console.log("開(kāi)始" + index, new Date().toLocaleString()); setTimeout(() => { resolve(index); console.log("結(jié)束" + index, new Date().toLocaleString()); }, parseInt(Math.random() * 10000)); }); }); } PromiseLimit(result).then(data => { console.log(data); });
修改測(cè)試代碼,新增隨機(jī)失敗邏輯
// 修改測(cè)試代碼 隨機(jī)失敗或者成功 const result = []; for (let index = 0; index < 10; index++) { result.push(function() { return new Promise((resolve, reject) => { console.log("開(kāi)始" + index, new Date().toLocaleString()); setTimeout(() => { if (Math.random() > 0.5) { resolve(index); } else { reject(index); } console.log("結(jié)束" + index, new Date().toLocaleString()); }, parseInt(Math.random() * 1000)); }); }); } PromiseLimit(result).then( data => { console.log("成功", data); }, data => { console.log("失敗", data); } );
7、async 和await 結(jié)合promise all
async function PromiseAll(promises,batchSize=10) { const result = []; while(promises.length > 0) { const data = await Promise.all(promises.splice(0,batchSize)); result.push(...data); } return result; }
這么寫(xiě)有2個(gè)問(wèn)題:
- 1、在調(diào)用
Promise.all
前就已經(jīng)創(chuàng)建好了promises
,實(shí)際上promise
已經(jīng)執(zhí)行了 - 2、你這個(gè)實(shí)現(xiàn)必須等前面
batchSize個(gè)promise resolve
,才能跑下一批的batchSize
個(gè),也就是promise all
全部成功才可以。
改進(jìn)如下:
async function asyncPool(array,poolLimit,iteratorFn) { const ret = []; const executing = []; for (const item of array) { const p = Promise.resolve().then(() => iteratorFn(item, array)); ret.push(p); if (poolLimit <= array.length) { const e = p.then(() => executing.splice(executing.indexOf(e), 1)); executing.push(e); if (executing.length >= poolLimit) { await Promise.race(executing); } } } return Promise.all(ret); }
使用:
const timeout = i => new Promise(resolve => setTimeout(() => resolve(i), i)); return asyncPool( [1000, 5000, 3000, 2000], 2,timeout).then(results => { ... });
到此這篇關(guān)于JavaScript異步操作中串行和并行的文章就介紹到這了,更多相關(guān)JavaScript異步操作串行和并行內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript前端分頁(yè)實(shí)現(xiàn)示例
這篇文章主要為大家介紹了JavaScript前端分頁(yè)實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07微信小程序 支付簡(jiǎn)單實(shí)例及注意事項(xiàng)
這篇文章主要介紹了微信小程序 支付簡(jiǎn)單實(shí)例的相關(guān)資料,這里參考官方文檔寫(xiě)的簡(jiǎn)單實(shí)例,并提出注意事項(xiàng),需要的朋友可以參考下2017-01-01微信小程序 滾動(dòng)到某個(gè)位置添加class效果實(shí)現(xiàn)代碼
這篇文章主要介紹了微信小程序 滾動(dòng)到某個(gè)位置添加class效果實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-04-04Skypack布局前端基建實(shí)現(xiàn)過(guò)程詳解
這篇文章主要為大家介紹了Skypack布局前端基建過(guò)程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07js 實(shí)現(xiàn)驗(yàn)證碼輸入框示例詳解
這篇文章主要為大家介紹了js 實(shí)現(xiàn)驗(yàn)證碼輸入框示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09