我正试图围绕链式AngularJS承诺中的错误处理。 我知道这种成功/失败的语法:
.then( function( departure )
{
$scope.departure = departure; // Response Handler #1
return travelService.getFlight( departure.flightID ); // Request #2
}, function( error )
{
//handle error
})
但是,我不知道如何将其应用于这样的链:
var FlightDashboard = function( $scope, user, flightService, weatherService )
{
travelService
.getDeparture( user ) // Request #1
.then( function( departure )
{
$scope.departure = departure; // Response Handler #1
return travelService.getFlight( departure.flightID ); // Request #2
})
.then( function( flight )
{
$scope.flight = flight; // Response Handler #2
return weatherService.getForecast( $scope.departure.date ); // Request #3
})
.then( function( weather )
{
$scope.weather = weather; // Response Handler #3
});
};
如果我需要针对这3个请求中的任何一个或全部的错误处理函数,该怎么办? 它会是这样的吗?如果确实如此,我需要从错误处理程序返回任何内容吗?
var FlightDashboard = function( $scope, user, flightService, weatherService )
{
travelService
.getDeparture( user ) // Request #1
.then( function( departure )
{
$scope.departure = departure; // Response Handler #1
return travelService.getFlight( departure.flightID ); // Request #2
}, function( error )
{
//handle request 1 error
})
.then( function( flight )
{
$scope.flight = flight; // Response Handler #2
return weatherService.getForecast( $scope.departure.date ); // Request #3
}, function( error )
{
//handle request 2 error
})
.then( function( weather )
{
$scope.weather = weather; // Response Handler #3
}, function( error )
{
//handle request 3 error
});
};
答案 0 :(得分:2)
是的,就像成功函数一样,错误处理函数也需要返回一个值。 then
函数返回的承诺由success
或error
回调的返回值解决。
这里的一个怪癖是,如果我们在错误回调中执行正常返回,则链中进一步的承诺将始终解析为sucess
。如果您希望传播承诺被拒绝承诺链中的承诺,则需要在error
回调中返回被拒绝的承诺。像这样:
var FlightDashboard = function( $scope, user, flightService, weatherService )
{
travelService
.getDeparture( user ) // Request #1
.then( function( departure )
{
$scope.departure = departure; // Response Handler #1
return travelService.getFlight( departure.flightID ); // Request #2
}, function( error )
{
return $q.reject(error)
})
.then( function( flight )
{
$scope.flight = flight; // Response Handler #2
return weatherService.getForecast( $scope.departure.date ); // Request #3
}, function( error )
{
return $q.reject(error)
})
.then( function( weather )
{
$scope.weather = weather; // Response Handler #3
}, function( error )
{
return $q.reject(error)
});
};