我想了解一次与 javascript 中的地图迭代器相关的概念。我想执行多个地图迭代器,我想出了以下解决方案。
await Promise.all({
arrOne.map(async first => {
arrTwo = //call another await operation
arrTwo.map(async second => {
arrThree = //call another await operation
arrThree.map(async third => {
//return await operation and result
})
})
})
})
我想实现的是并行处理数据,我认为通过Promise.all我们可以实现。我想知道这是否是好方法。
我还想处理一个大数据集。上述方法是否有效,因为我也在考虑批量处理数据。
永远不要尝试这个,但我认为你需要这样的东西:
await Promise.all(
arrOne.map(async lvl1 => {
return await Promise.all(
lvl1.map(async lvl2 => {
return await Promise.all(
lvl2.map(async lvl3 => {
return await Promise.all(lvl3 => [lvl3 || 'something']);
})
);
})
);
})
);
Promise.all
在每个可迭代数组中。
如果你想以并行方式处理任务,你应该做
Promise.all
像这样将任务值作为数组传递:
Promise.all([ task1(), task2(), task3(), ... ]);
任务以函数的形式表示,可以用任何命令填充,包括地图迭代器。例如:
let httpRequest = (method, theUrl) => {
return new Promise((resolve, reject) => {
$.ajax({
type: method,
url: theUrl,
success: (res)=>{
resolve(res);
},
error: (err) => {
reject(err);
}
});
});
}
let getTime = () => {
return (new Date()).toISOString().replace('T',' ').replace('Z','');
}
(async() => {
await Promise.all([
(async () => {
console.log('arrOne start:',getTime());
let arrOne = (await httpRequest('GET', 'https://dummyjson.com/products')).products;
arrOne = arrOne.map(arr => `${arr.id} ${arr.title}`);
console.log('arrOne finish:',getTime());
return arrOne;
})(), (async () => {
console.log('arrTwo start:',getTime());
let arrTwo = (await httpRequest('GET', 'https://dummyjson.com/carts')).carts;
arrTwo = arrTwo.map(arr => `${arr.id} ${arr.products[0].title}`);
console.log('arrTwo finish:',getTime());
return arrTwo;
})(), (async () => {
console.log('arrThree start:',getTime());
let arrThree = (await httpRequest('GET', 'https://dummyjson.com/users')).users;
arrThree = arrThree.map(arr => `${arr.id} ${arr.firstName}`);
console.log('arrThree finish:',getTime());
return arrThree;
})()
]).then((res)=>{
console.log('arrOne:\n',res[0]);
console.log('arrTwo:\n',res[1]);
console.log('arrThree:\n',res[2]);
});
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>