If you want to create a custom promise using the $q service and resolve it after the second call is completed, you can follow this example:
angular.module('mymodule').factory('FruitService', function($http, $q) {
return {
getFruitInfoDetails: function() {
// create a new promise
var deferred = $q.defer();
// First API call
$http.get("fruitInfo").then(function(fruitInfo) {
// Second API call
$http.get("fruitDetails").then(function(fruitDetails) {
deferred.resolve({
fruitInfo: fruitInfo,
fruitDetails:fruitDetails
});
});
});
return deferred.promise;
}
};
});
Alternatively, you can use $q.all() to wait for both requests to complete before resolving the promise, resulting in cleaner code with less indentation:
angular.module('mymodule').factory('FruitService', function($http, $q) {
return {
getFruitInfoDetails: function() {
// create a new promise
var deferred = $q.defer();
// First API call
var infoPromise = $http.get("fruitInfo");
var detailsPromise = $http.get("fruitDetails");
$q.all([infoPromise, detailsPromise]).then(function(data) {
deferred.resolve({
fruitInfo: data[0],
fruitDetails: data[1]
})
});
return deferred.promise;
}
};
});
This code snippet demonstrates how to retrieve a list of specified fruits:
angular.module('mymodule').factory('FruitService', function($http, $q) {
return {
getFruitInfoDetails: function(fruit) {
// create a new promise
var deferred = $q.defer();
// Assuming the fruit parameter is part of the API path
var infoPromise = $http.get("fruitInfo/" + fruit);
var detailsPromise = $http.get("fruitDetails/" + fruit );
$q.all([infoPromise, detailsPromise]).then(function(data) {
deferred.resolve({
fruitInfo: data[0],
fruitDetails: data[1]
})
});
return deferred.promise;
},
getFruitList: function(fruits) {
var deferred = $q.defer();
// Map the list of fruits to a list of promises for fruit info
var allPromises = fruits.map(function (fruit) {
return this.getFruitInfoDetails(fruit);
});
// Wait for all promises to resolve before resolving our own promise
$q.all(allPromises).then(function(allTheFruitInfoDetails) {
deferred.resolve(allTheFruitInfoDetails);
});
return deferred.promise;
}
};
});