[英]Promise.all with for loop in node.js
我在 node.js 中收集从 1 到 10 的每个页面的信息作为 API。
现在我使用这个代码。
async function myWork() {
let results = []
let tmp
let param
for (i=1; i<11; i++) {
param = {'page': i}
tmp = await callMyApi(param) // return a list
results.push(...tmp)
}
return results
}
在这种情况下,每个 callMyApi 的行为都类似于同步。
但我不在乎页面顺序。
所以,为了加快速度,我想使用 promise.all 之类的东西来并行处理它。
在这种情况下,如何在 for 循环中使用 promise.all?
您可以将 Promise.all() 与 concat() 一起使用。
async function myWork() {
let results = [];
let promises = [];
let param;
for (i=1; i<11; i++) {
let param = {'page': i}
let tmpPromise = callMyApi(param);
promises .push(tmpPromise);
}
//promises is now an array of promises, and can be used as a param in Promise.all()
let resolved = await Promise.all(promises);
//resolved is an array of resolved promises, each with value returned by async call
let indivResult = resolved.forEach(a =>
results = results.concat(a));
//for each item in resolved array, push them into the final results using foreach, you can use different looping constructs here but forEach works too
return results;
}
下面的例子:
async function myWork() {
let results = [];
let param;
for (i = 1; i < 11; i++) {
param = { page: i };
results.push(callMyApi(param));
}
const res = await Promise.all(results);
return res.flat();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.