dman dman - 18 days ago 6
AngularJS Question

Angular $http requests not fulfilling in Promise.all

I have a array of http requests that I am using in an

Promise.all
. The issue is that when
Promise.all
is fulfilled,
console.log(values);
shows the original
dealers
array instead of the resolved http requests response object. Why am I not getting the resolved http requests in the
Promise.all
?

function getDealer(regionMarketDealer) {
var params = {
url: API_BASE_URI + 'service/ppv/' + regionMarketDealer,
method: 'GET'
};

return $http(params);
}

function getAllMarketDealers(dealers) {
var dealerHttpRequests = dealers.filter(function(dealer) {
if (dealer.name !== 'All') {
var promise = getDealer(dealer.name);
return promise;
} else {
return false;
}
});

Promise.all([dealerHttpRequests])
.then(function(values) {
console.log(values);
});
}

Answer

.filter is used to filter your array by returning true or false in a function and that then creates a new array with the filtered result.

If you then want to create promises of the filtered array you should then use .map and return a promise

function getDealer(regionMarketDealer) {
    var params = {
      url: API_BASE_URI + 'service/ppv/' + regionMarketDealer,
      method: 'GET'
    };

    return $http(params);
  }

function getAllMarketDealers(dealers) {
  var dealerHttpRequests = dealers.filter(function(dealer) {
        return dealer.name !== 'All';
    })
    .map(function(dealer) {
        return getDealer(dealer.name);
    });

  Promise.all(dealerHttpRequests)
    .then(function(values) {
      console.log(values);
    });
}
Comments