本文主要讲解“如何在JavaScript异步操作中使用串行和并行”。本文的解释简单明了,易学易懂。现在,请跟随边肖的思路,一起学习和学习“如何在JavaScript异步操作中使用串行和并行”!
1、前言
写下js中的es5和es6的异步函数、串行执行和并行执行的方案。与串行和并行结合使用的示例。
2、es5方式
在es6问世之前,社区nodejs中就有一个回叫地狱的承诺方案。如果有多个异步函数,如何安排执行顺序,如何更快地完成所有异步函数,然后执行下一步?这里就出现了js的串行执行和并行执行的问题。
3、异步函数串行执行
varitems=[1,2,3,4,5,6];
var results=[];
functionasync(arg,callback){ 0
Console.log('参数为' arg ',1秒后返回结果');
setTimeout(函数(){回调(arg * 2);},1000);
}
functionfinal(值){ 0
Console.log('已完成: ',值);
}
功能系列(项目){ 0
if(项目){ 0
async(项目、函数(结果))
results.push(结果);
return series(items . shift());//递归执行所有数据。
});
}else{
return final(results[results . length-1]);
}
}
series(items . shift());00-1010以上功能一个接一个执行,下一个在最后一次执行后执行,类似于es6中的async和wait(ES5后统称es6)。有没有类似诺言的平行执行?
可以如下写:
varitems=[1,2,3,4,5,6];
var results=[];
functionasync(arg,callback){ 0
Console.log('参数为' arg ',1秒后返回结果');
setTimeout(函数(){回调(arg * 2);},1000);
}
functionfinal(值){ 0
Console.log('已完成: ',值);
}
Items.foreach(函数(项){//循环完成
async(项目、函数(结果))
results.push(结果);
如果(结果。长度==项目。length){//判断执行的函数个数是否等于要执行的函数个数。
最终结果
esults.length - 1]);
}
})
});
5、异步函数串行执行和并行执行结合
假如并行执行很多条异步(几百条)数据,每个异步数据中有很多的(https)请求数据,势必造成tcp 连接数不足,或者堆积了无数调用栈导致内存溢出。所以并行执行不易太多数据,因此,出现了并行和串行结合的方式。
代码可以如下书写:
var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
var running = 0;
var limit = 2;
function async(arg, callback) {
console.log('参数为 ' + 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天然自带串行和并行的执行方式,例如串行可以用async和await(前文已经讲解),并行可以用promise.all等等。那么针对串行和并行结合,限制promise all并发数量,社区也有一些方案,例如
tiny-async-pool、es6-promise-pool、p-limit
简单封装一个promise all并发数限制解决方案函数
function PromiseLimit(funcArray, limit = 5) { // 并发执行5条数据
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前就已经创建好了promises,实际上promise已经执行了 -
2、你这个实现必须等前面
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异步操作中串行和并行这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是,小编将为大家推送更多相关知识点的文章,欢迎关注!
内容来源网络,如有侵权,联系删除,本文地址:https://www.230890.com/zhan/104193.html
