Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run async functions in parallel?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading