Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Angular how can we make a call after completing bunch of asynchronous calls

Tags:

angularjs

q

This is my code in controller

myFactory.getPoints().success(function (data) {
    $scope.points = data;
});

myFactory.getStates().success(function (data) {
    $scope.states = data;
});

myFactory.getLeases().success(function (data) {
    $scope.leases = data;
});

I am expecting $scope.leases gets the value after $scope.points and $scope.states gets their values. I learned that $q with .then is not synchronous. Is that right?

Answer: I have derived below from the answers

$q.all([
        myFactory.getPoints().success(function (data) {
            $scope.Points = data;
        }).error(function (data) {
            $scope.error = "An Error has occurred while loading Points! " + data.ExceptionMessage;
        }),   //more, more, more

    ]).then(function () {
        myFactory.getLease().success(function (data) {
            $scope.leases = data;
        }).error(function (data) {
            $scope.error = "An Error has occurred while loading Leases! " + data.ExceptionMessage;
        })
});
like image 633
Venu Avatar asked Nov 30 '25 02:11

Venu


2 Answers

You can chain promises together in order to have them execute synchronously:

myFactory.getPoints().success(function (data) {
    $scope.points = data;

    return myFactory.getStates();
})
.success(function (data) {
    $scope.states = data;

    return myFactory.getLeases();
})
.success(function (data) {
    $scope.leases = data;
});
like image 183
Josh Avatar answered Dec 02 '25 20:12

Josh


The problem is success() does return the original promise. then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

So a proper solution is

$q.all([
    myFactory.getPoints().then(function (response) {
      $scope.points = response.data;
      return response.data;
    }),

    myFactory.getStates().then(function (response) {
      $scope.states = response.data;
      return response.data;
    }),

    myFactory.getLeases().then(function (response) {
      $scope.leases = response.data;
      return response.data;
  })
]).then(function(responses) {
   // xxx
});
like image 40
Rebornix Avatar answered Dec 02 '25 18:12

Rebornix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!