.then
is a promises
.success
and .error
is a callback.
Why callbacks or Promises?
1 . Promises can handle global errors.
2 . Promises can be chained (you don't have this encapsulation like callbacks)
P = promise,
R = response,
E = error.
1:
P1(R1)
.P2(R2)
.P3(R3, E3)
Error 3 will be called if there is an error in promise 1, 2 or 3.
That is not possible with callbacks.
2:
If you have 3 promises:
P1(R1, E1)
.P2(R2, E2)
.P3(R3,E3)
If you have 3 callbacks
P1().success(P2().success(P3().success().error()).error()).error()
EDIT
.service('Auth', function(){
this.isLoggedIn = function(){
return $http.get('url/isLoggedIn');
};
})
.service('getData', function(){
this.name = function(){
return $http.get('url/data/name');
}
})
.controller('MyCTRL', ['Auth', 'getData', function(auth, getData){
Auth.isLoggedIn().then(function(resp){
return getData.name(); //By sending a value back inthe response, next response is called
})
.then(function(res){
//Here we are
}, function(err){
//Global error.
//This will be called in P1 or P2
})
}]);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…