3

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;
        })
});

2 Answers 2

4

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;
});
2
  • Not necessarily 3 promises. I have 5 promises which can be called asynchronously and the 6th call should be after the completion of all the other 5 calls.
    – Venu
    Feb 12, 2015 at 5:43
  • @Venu check my answer you can get an idea how to chain a promise after five other functions.
    – Rebornix
    Feb 12, 2015 at 5:45
2

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
});

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.