stackunderflow
stackunderflow

Reputation: 1714

Promise.all on array of promises with parameter

How can I add an array of promises to Promise.all when a parameter is passed to each promise?

For example;

var config = {
  name: [
    function(val) {
      return new Promise(function(resolve, reject) {
        resolve('This is ok')
      })
    },
    function(val) {
      return new Promise(function(resolve, reject) {
        resolve('This is ok')
      })
    }
  ],
  gender: [
    function(val) {
      return new Promise(function(resolve, reject) {
        resolve('This is ok')
      })
    },
    function(val) {
      return new Promise(function(resolve, reject) {
        reject('This is NOT ok')
      })
    }
  ]
}

I essentially want to to do Promise.all(config[name], ...). This will actually take place within a loop so that I can iterate over a form object, passing each key to get an array of associated promises and passing the value to each promise.

EDIT Fiddle which implements the accepted answer, for the curious.

Upvotes: 17

Views: 21363

Answers (1)

Lyubomir
Lyubomir

Reputation: 20027

Use map to call the functions and return an array of promises.

Promise.all(config[name].map(callback => callback(val))
   .then(values => { 
       // executed when all promises resolved, 
       // values is the array of values resolved by the promises
   })
   .catch(err => {  
     // catch if single promise fails to resolve
   });

You can read more about Promise.all here.

Upvotes: 16

Related Questions