Rishabh Rishabh - 1 month ago 6
AngularJS Question

chain controller functions/code in sequential order and handle errors

I have some controller functions for different tasks which may call service functions (which in turn contain $http requests). Ex:

// this should be run first
function getData1(request) {
dataService.getData1(request).then(function success(response) {
return response;
})
};

// this should run after getData1()
function getData2(request) {
dataService.getData2(request).then(function success(response) {
return response;
})
};


I am calling these functions from a central place on a certain event (say, when user changes the input/request data):

$scope.loading = true;
$scope.$watch('input', function(newValue, oldValue) {
if(newValue !== oldValue) {
request = newValue;
$scope.data1 = getData1(request);
$scope.data2 = getData2(request);
$scope.loading = false;
}
});


But as far as I know, the
getData1()
and
getData2()
make asynchronous requests and it might cause
$scope.loading = false
before the data is loaded.

Also, if there are any errors in one or more requests, the
$scope.data1
or
$scope.data2
variables will have the rejected Promise values, right?

So, what are the 'best practices' to chain such functions and also handle errors if there are any? Please help.

Answer

getData1 and getData2 (which in turn calls $http) returns promise.

var promise1 = dataService.getData1(request);
var promise2 = dataService.getData2(request);

you can use $q.all(). Pass promise1 and promise2 to $q.all.This does not guarantee that promise will resolve in sequence.

If one promise fails, the combined promise fails.
If all promises succeed, the combined promise succeeds.

example link for $q.all

For sequential execution,

dataService.getData1(request1).then(function(response1) {
    //do your stuff
    return dataService.getData2(request2);
}).then(function(response2) {
    //response2 - response of dataService.getData2(request2)
    //do your stuff
}).catch(function(error) {
    //on error if any of this fails.
})
Comments