Search code examples
javascriptnode.jspromisepromise.all

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!


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()))