JavaScript異步操作中串行和并行
1、前言
本文寫一下js
中es5
和es6
針對異步函數(shù),串行執(zhí)行和并行執(zhí)行的方案。已經串行和并行結合使用的例子。
2、es5方式
在es6出來之前,社區(qū)nodejs
中針對回調地獄,已經有了promise
方案。假如多個異步函數(shù),執(zhí)行循序怎么安排,如何才能更快的執(zhí)行完所有異步函數(shù),再執(zhí)行下一步呢?這里就出現(xiàn)了js的串行執(zhí)行和并行執(zhí)行問題。
3、異步函數(shù)串行執(zhí)行
var items = [ 1, 2, 3, 4, 5, 6 ]; var results = []; function async(arg, callback) { console.log('參數(shù)為 ' + arg +' , 1秒后返回結果'); 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ù)是一個一個執(zhí)行的,上一個執(zhí)行結束再執(zhí)行下一個,類似es6
(es5之后統(tǒng)稱es6)中 async 和await,那有沒有類似promise.all
這種,所有的并行執(zhí)行的呢?
可以如下寫:
var items = [ 1, 2, 3, 4, 5, 6 ]; var results = []; function async(arg, callback) { console.log('參數(shù)為 ' + arg +' , 1秒后返回結果'); 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í)行完畢的個數(shù)是否等于要執(zhí)行函數(shù)的個數(shù) final(results[results.length - 1]); } }) });
5、異步函數(shù)串行執(zhí)行和并行執(zhí)行結合
假如并行執(zhí)行很多條異步(幾百條)數(shù)據(jù),每個異步數(shù)據(jù)中有很多的(https)請求數(shù)據(jù),勢必造成tcp 連接數(shù)不足,或者堆積了無數(shù)調用棧導致內存溢出。所以并行執(zhí)行不易太多數(shù)據(jù),因此,出現(xiàn)了并行和串行結合的方式。
代碼可以如下書寫:
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秒后返回結果'); 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
(前文已經講解),并行可以用promise.all等等。那么針對串行和并行結合,限制promise all
并發(fā)數(shù)量,社區(qū)也有一些方案,例如
tiny-async-pool、es6-promise-pool、p-limit
簡單封裝一個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)); }
使用:
// 測試代碼 const result = []; for (let index = 0; index < 10; index++) { result.push(function() { return new Promise((resolve, reject) => { console.log("開始" + index, new Date().toLocaleString()); setTimeout(() => { resolve(index); console.log("結束" + index, new Date().toLocaleString()); }, parseInt(Math.random() * 10000)); }); }); } PromiseLimit(result).then(data => { console.log(data); });
修改測試代碼,新增隨機失敗邏輯
// 修改測試代碼 隨機失敗或者成功 const result = []; for (let index = 0; index < 10; index++) { result.push(function() { return new Promise((resolve, reject) => { console.log("開始" + index, new Date().toLocaleString()); setTimeout(() => { if (Math.random() > 0.5) { resolve(index); } else { reject(index); } console.log("結束" + index, new Date().toLocaleString()); }, parseInt(Math.random() * 1000)); }); }); } PromiseLimit(result).then( data => { console.log("成功", data); }, data => { console.log("失敗", data); } );
7、async 和await 結合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; }
這么寫有2個問題:
- 1、在調用
Promise.all
前就已經創(chuàng)建好了promises
,實際上promise
已經執(zhí)行了 - 2、你這個實現(xiàn)必須等前面
batchSize個promise resolve
,才能跑下一批的batchSize
個,也就是promise all
全部成功才可以。
改進如下:
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 => { ... });
到此這篇關于JavaScript異步操作中串行和并行的文章就介紹到這了,更多相關JavaScript異步操作串行和并行內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
微信小程序 滾動到某個位置添加class效果實現(xiàn)代碼
這篇文章主要介紹了微信小程序 滾動到某個位置添加class效果實現(xiàn)代碼的相關資料,需要的朋友可以參考下2017-04-04