When working with multiple API requests, executing them in parallel can improve performance and efficiency. AngularJS provides the $q
service, which includes the $q.all()
method to handle multiple promises simultaneously.
Why Use $q.all()
?
Executes multiple API calls in parallel
Improves performance instead of waiting for each request sequentially
Returns results when all promises are resolved
Handles failures gracefully
1. Basic Usage of $q.all()
$q.all()
takes an array or object of promises and waits until all are resolved or one fails.
Example: Making Two API Calls in Parallel
app.controller("MyController", function($scope, $http, $q) {
var apiCall1 = $http.get("https://api.example.com/users");
var apiCall2 = $http.get("https://api.example.com/orders");
$q.all([apiCall1, apiCall2]).then(function(responses) {
$scope.users = responses[0].data; // Response from first API
$scope.orders = responses[1].data; // Response from second API
}).catch(function(error) {
console.error("Error in API calls: ", error);
});
});
🔹 Calls both Users API and Orders API in parallel
🔹 Waits for both to complete before updating $scope
🔹 Handles errors centrally using .catch()
2. Using $q.all()
with Named Promises
Instead of using an array, $q.all()
also supports objects for better readability.
app.controller("MyController", function($scope, $http, $q) {
var apiCalls = {
users: $http.get("https://api.example.com/users"),
orders: $http.get("https://api.example.com/orders"),
products: $http.get("https://api.example.com/products")
};
$q.all(apiCalls).then(function(responses) {
$scope.users = responses.users.data;
$scope.orders = responses.orders.data;
$scope.products = responses.products.data;
}).catch(function(error) {
console.error("API call failed: ", error);
});
});
🔹 More readable compared to arrays
🔹 Responses are accessed by property names instead of indexes
3. Handling Partial Failures
If one API fails, $q.all()
rejects the entire promise. To handle partial failures, use individual .catch()
blocks.
app.controller("MyController", function($scope, $http, $q) {
var apiCall1 = $http.get("https://api.example.com/users").catch(function(error) {
console.error("Users API failed: ", error);
return { data: [] }; // Return empty array instead of failing completely
});
var apiCall2 = $http.get("https://api.example.com/orders").catch(function(error) {
console.error("Orders API failed: ", error);
return { data: [] }; // Prevent breaking the flow
});
$q.all([apiCall1, apiCall2]).then(function(responses) {
$scope.users = responses[0].data;
$scope.orders = responses[1].data;
});
});
🔹 Uses .catch()
for individual APIs to prevent complete failure
🔹 Returns empty data to ensure UI does not break
4. Combining $q.all()
with Data Processing
Often, API responses need to be processed before displaying.
app.controller("MyController", function($scope, $http, $q) {
var usersPromise = $http.get("https://api.example.com/users");
var ordersPromise = $http.get("https://api.example.com/orders");
$q.all([usersPromise, ordersPromise]).then(function(responses) {
var users = responses[0].data;
var orders = responses[1].data;
// Process and link orders with users
$scope.userOrders = users.map(user => {
user.orders = orders.filter(order => order.userId === user.id);
return user;
});
}).catch(function(error) {
console.error("Error fetching data: ", error);
});
});
🔹 Merges data between APIs
🔹 Uses .map()
and .filter()
for custom data processing
5. Using $q.all()
with Service Calls
For better code reusability, use $q.all()
inside an AngularJS service.
app.factory("ApiService", function($http, $q) {
return {
fetchData: function() {
return $q.all({
users: $http.get("https://api.example.com/users"),
orders: $http.get("https://api.example.com/orders")
});
}
};
});
app.controller("MyController", function($scope, ApiService) {
ApiService.fetchData().then(function(responses) {
$scope.users = responses.users.data;
$scope.orders = responses.orders.data;
}).catch(function(error) {
console.error("API error: ", error);
});
});
🔹 Encapsulates API calls in a service
🔹 Controller remains clean and focused