1

I need to do 2 http requests on angularjs, but I need that the second request only be executed after the first request has been resolved. Because -> And I need of the return of the two requests at the same time. Which is the best way to do this?

I do an test, with the code below, however the two promises are executed at the same time. How can I do for that the second promise only be executed after the first promise has been resolved?

$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 have managed to solve the problem with this code, but it does not seem to me the best way to do this. How can I improve this code?

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')
});
  • Read this [post](https://toddmotto.com/promises-angular-q), it may be of help. – Jax Sep 07 '17 at 15:12
  • "*Because I need of the return of the two requests at the same time.*" - that sounds more like the first solution? – Bergi Sep 07 '17 at 19:33
  • Apart from the global `categories` and `tags` variables that should definitely be avoided, the second seems like a quite fine solution. Of course there are [many many more approaches](https://stackoverflow.com/q/28250680/1048572) to access results from a sequential promise chain at the same time. – Bergi Sep 07 '17 at 19:35
  • Thanks for help. I have already find an solution to solve the problem. See the updates. Thank you again. ;) – Bryan Didur Sep 14 '17 at 01:37

1 Answers1

0

this might be a bit nicer?

getData(api_url('categories'))
  .then(function(response) {
    $scope.categories = response.data;

    return getData(api_url('tags'));
  }).then(function(response) {
    $scope.tags = response.data;
  }).catch(function(response) {
    notify('Cannot get data for articles register!', 'error');
  });