Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 472
stackunderflow Avatar asked Dec 20 '16 12:12

stackunderflow


1 Answers

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.

like image 51
Lyubomir Avatar answered Oct 12 '22 00:10

Lyubomir