How can I make 2 HTTP requests in AngularJS where the second request is only executed after the first one has been resolved? Also, I need both requests' returns simultaneously. What is the best approach for achieving this?
I attempted to tackle this issue with the code provided below, but both promises are being executed concurrently. How can I ensure that the second promise is only triggered once the first promise resolves?
$q.all([
getData(api_url('categories')),
getData(api_url('tags')), // This promise must only be executed after the promise above has been resolved
]).then(function (response) {
$scope.categories = response[0];
$scope.tags = response[1];
}).catch(function (error) {
notify('Cannot get data for articles register!', 'error');
});
[UPDATE] I found a solution using the code below, but I don't think it's the most optimal way to handle this situation. How can I enhance this code further?
getData(api_url('categories')).then(function (response) {
categories = response.data;
return getData(api_url('tags')).then(function (response) {
tags = response.data;
$scope.categories = categories;
$scope.tags = tags;
});
}).catch(function (response) {
notify('Cannot get data for articles register!', 'error');
});
[SOLUTION]
var categoriesPromise = getData(api_url('categories'));
var tagsPromise = categoriesPromise.then(function (response) {
return getData(api_url('tags'));
});
$q.all([categoriesPromise, tagsPromise]).then(function (response) {
$scope.categories = response[0].data;
$scope.tags = response[1].data;
}).catch(function (response) {
notify('Cannot get data for articles register!', 'error')
});