Promise.all by promises array with parameter

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

For instance:

 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 really want to do Promise.all(config[name], ...) . This will happen in a loop so that I can iterate over the form object, passing each key to get an array of related promises and passing the value to each promise.

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

+6
source share
1 answer

Use map to call functions and return the promises array.

 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 }); 

Read more about Promise.all here .

+7
source

Source: https://habr.com/ru/post/1013336/


All Articles