【发布时间】:2016-10-21 15:45:09
【问题描述】:
我有一些用于不同任务的控制器函数,它们可能会调用服务函数(这些函数又包含 $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 值,对吧?
那么,链接这些函数并处理错误(如果有)的“最佳实践”是什么?请帮忙。
【问题讨论】:
-
你可以做一个回调链,即在getData1()的回调中调用getData2()。这是最简单的方法。但是对于更复杂的用途,你可以考虑使用 Promise。
-
我不想使用回调链。它使 getData2() 调用依赖于 getData1()。我想分离关注点,即从一个中心位置控制这种链接。
-
如果不想使用回调,可以尝试使用promise,或者一些es6的特性比如async/await