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

Calling a promise.all with a function using dynamically generated parameters

Hello I am trying to run the same function asynchronously using different parameters but cannot figure out how to store the functions without running them before the promise all.

Here’s a simplified example of what I am trying to do:

const myFunc = async(paramsAsArray) => {
    // does stuff
}

let paramArray = [ [a,b], [c, d], [e, f] ]
let funcArray = []

for (let i = 0; i < paramArray.length; i++) {

    funcArray.push(myFunc(paramArray[i]))

}

const response = await Promise.all(funcArray)

My functions keep running in the for loop before I can use the promise.all(). Does anyone know what I can do to make them run a using a promise all? Any help or suggestions is appreciated, thanks!

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

>Solution :

Wrap your function in another function so it doesn’t get called immediately. then call it inside Promise.all

funcArray.push(() => myFunc(paramArray[i]))`

const response = await Promise.all(funcArray.map(f=> f()))
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