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;
})
});
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;
});
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With