Take data out of a function

2

Good, I need to get the variable "users" of this function and the for loop, I thought about using promises but I'm new with that and I can not find the round

  var ids = [
    "RtSG7NApoda9ycDRd7vm",
    "TnT9XOXnkD1Ra5ROJERR",
    "55fAOlOlejE3v0EUU4z9"
   ];

   var users = [];



 for(var i = 0; i < ids.length; i++){
  getData(ids[i]).then(function (data) {
   users.push(data);
  });
 }
    
asked by Santiago D'Antuoni 23.01.2018 в 22:04
source

1 answer

3

In this case it is necessary to make a tail of promises, using the method all of class Promise .

Documentation Promise.all ()

To perform the procedure you need the following:

var ids = [1, 2, 3];

// Multiples datos
var data = function (ids) {
  var promises = [];

  for(var i = 0; i < ids.length; i++) {
    promises.push(getData(ids[i]));
  }

  return Promise.all(promises);
}

// Ejecutar
data(ids).then(function (users) {
  console.log('Data:', users);
}, function (reason) {
  console.error('Exception', reason);
});
  

In the event that any included promise returns by reject() the Promise.all() will enter the second callback of then() and will show the reason why it was not executed correctly.

    
answered by 23.01.2018 / 22:23
source