这使用了当被取消$timeout
时被拒绝的承诺。$timeout
catch 处理程序拒绝第二个计时器并立即执行其操作。
$scope.data1_timeout = $timeout(function() {
// some action
}, 2000);
$scope.data2_timeout = $timeout(function() {
// some action
}, 4000);
$scope.data1_timeout.catch(function(){
$timeout.cancel($scope.data2_timeout);
//same actions here as in data2_timeout
})
将 data2_timeout 功能封装在命名函数中并从两个地方调用它会更有意义,如下所示:
$scope.data1_timeout = $timeout(function() {
// some action
}, 2000);
function someAction2() {
//some action
}
$scope.data2_timeout = $timeout(someAction2, 4000);
$scope.data1_timeout.catch(function(){
$timeout.cancel($scope.data2_timeout);
someAction2();
})
注意:如果意图是让 data2 操作等待 data1_timeout 完成或被取消,那么不要将 data2 设置为超时,只需将其添加.finally()
为 data1_timeout 承诺的回调即可。
$scope.data1_timeout = $timeout(function() {
// some action
}, 2000);
$scope.data1_timeout.finally(function() {
// do data2 stuff here.
// Guaranteed to run, after data1_timeout completes or is canceled.
});