Home > Enterprise >  Calling a promise.all with a function using dynamically generated parameters
Calling a promise.all with a function using dynamically generated parameters

Time:02-24

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!

CodePudding user response:

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

CodePudding user response:

myFunc(paramArray[i]) calls the function immediately. You are calling it, so you are not pushing the function itself to the array, but its returned value. Also, the Promise resolution starts immediately, not in the Promise.all.

To push the function itself without calling it, and still passing it parmameters, use .bind :

funcArray.push(myFunc.bind(this, paramArray[i]))

You can also build your array using .map() :

const funcArray = paramArray.map( params => myFunc.bind(this, params));
  • Related