0

I want to return promise.all() with sources variable locally defined below so i could consume the promise when i call sourceRequest.then((sources)=>{//do something}) here's my code:

var sourceRequest=(...countries)=>{
    var sources=[];
    var promisesCollection=[];
    for(var country of countries)
    {
      var promise=this._vm.$axios.get('/sources',{params:{ country,language:'en'}})
      .then(response=>{
        sources.push(response.data.sources);
      });
      promisesCollection.push(promise); 
    }

    Promise.all(promisesCollection).then(()=>{
      return new Promise((resolve)=>resolve(sources));
    })
  };
  sourceRequest('in').then((sources)=>console.log(sources));

The problem is i get undefined in console The workaround: i have a workaround to this but the problem is i want the function to return sources and not api requests responses:

//this works
  var sourceRequest=(...countries)=>{
    var promisesCollection=[];
    for(var country of countries)
    {
      var promise=this._vm.$axios.get('/sources',{params:{ country,language:'en'}})
      promisesCollection.push(promise); 
    }

    return Promise.all(promisesCollection);
  };

   sourceRequest('in').then((response)=>{console.log(response)});
Abdullah Sohail
  • 355
  • 4
  • 8

2 Answers2

0

Then you just need a step that replaces the list of responses with the list of sources.

const promisedSources = Promise.all(promisesCollection)
                          .then(responses => 
                              responses.map(response => response.data.sources)
                          );
return promisesSources;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

You're not returning anything from sourceRequest, so it returns undefined, not a Promise.

While you could fix it by returning the Promise.all:

return Promise.all(promisesCollection).then(() => {

It would be more elegant to avoid the explicit Promise construction antipattern as well. Map the responses to their .data.sources:

const sourceRequest = (...countries) => {
  const promisesCollection = [];
  for (const country of countries) {
    promisesCollection.push(this._vm.$axios.get('/sources', {
        params: {
          country,
          language: 'en'
        }
    }));
  }

  return Promise.all(promisesCollection).then(
    responsesArr => responsesArr.map(response => response.data.sources)
  );
};
sourceRequest('in').then(console.log);

Or, with .map alone, instead of a for loop:

const sourceRequest = (...countries) => {
  return Promise.all(countries.map(country => (
    this._vm.$axios.get('/sources', {
        params: {
          country,
          language: 'en'
        }
    })
      .then(response => response.data.sources))
  ));
};
sourceRequest('in').then(console.log);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320