链控制器功能/代码按顺序排列并处理错误

时间:2016-10-21 06:44:36

标签: angularjs angular-promise

我有一些控制器功能用于不同的任务,可以调用服务功能(其中包含$ http请求)。例如:

// 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;
    })
};

我从某个事件的中心位置调用这些函数(例如,当用户更改输入/请求数据时):

$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;
    }
});

但据我所知,getData1()getData2()会发出异步请求,并且在加载数据之前可能会导致$scope.loading = false

此外,如果一个或多个请求中存在任何错误,$scope.data1$scope.data2变量将具有被拒绝的Promise值,对吧?

那么,链接这些函数的“最佳实践”是什么,如果有的话还会处理错误?请帮忙。

1 个答案:

答案 0 :(得分:2)

getData1 and getData2(反过来调用$http)会返回promise

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

您可以使用$q.all()。将promise1promise2传递给$q.all。这并不能保证承诺会按顺序解决。

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

example link for $q.all

对于顺序执行,

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.
})
相关问题