Advertisements
A nodeJS script. I have a function in it:
async myFunc1(a, b, c) {
//.......
}
which returns some value but not Promise
. I used to run it as this:
let a1 = await myFunc1(1, "fds", 99);
Now I need to run dozens of them at the same time, and the input of the amount of them, with the arguments, comes from the user.
let lines = readDataFromUserProvidedFile();
for (let i = 0; i < lines; i++) {
//
//how to run all the myFunc1(...) in parallel??
//and then print out a result of each?
//(?)
myFunc1(lines[i], i, i*2);
}
How will I run them in parallel in such a way? And when a subsequent one returns a result, I want to print it right away.
For the function it takes around 10 minutes to return a value. It doesn’t do calculations, it waits for a result from remote web service.
>Solution :
You can create a collection of promises that will be executed in parallel and then iterate-await on the collection:
Pseudo-code:
let lines = readDataFromUserProvidedFile();
const promises = lines.map((line, index) => myFunc1(line, index, index * 2));
// await the resolution of all promises and print the results as they become available
for await (const result of promises) {
console.log(result);
}