Promise.all在node.js中带有for循环



我在node.js.中作为API收集从1到10的每个页面的信息

现在我使用这个代码。

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的行为类似于sync。

但我不在乎页面顺序。

所以,为了加快速度,我想使用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();
}

最新更新