这个 angularJS 代码的目的是什么?
What is purpose of this angularJS code?
有人可以向我解释这段代码的作用吗?我知道它获取国家并将它们推送到网页中显示的列表中,但为什么呢?我认为 $scope.countries = service.query() 就足够了还是这种方式可以避免异步问题?
$q.all([$scope.address.$promise, $scope.countrys.$promise]).then(function() {
if (!$scope.address.country.id) {
return $q.reject();
}
return Country.get({id : $scope.address.country.id}).$promise;
}).then(function(country) {
$scope.countrys.push(country);
});
代码注释中的说明。这是使用 promise 机制的有条件数据加载过程。如果对您来说还不够,请尝试更详细地说明您的问题
// if address and countries was loaded (probably from ajax request)
$q.all([$scope.address.$promise, $scope.countrys.$promise]).then(function() {
// if address doesn't exist reject all actions
if (!$scope.address.country.id) {
return $q.reject();
}
// otherwise load country based on address field as a promise
return Country.get({id : $scope.address.country.id}).$promise;
}).then(function(country) {
// when loading process is finished add country to dataset
$scope.countrys.push(country);
});
$q.all([promise1, promise2, ...])
Combines multiple promises into a single promise that is resolved when
all of the input promises are resolved.
service.query()
必然会return一个promise,在异步调用完成时解析。使用 promise 设置范围 属性(毫无疑问,您将绑定到某种形式的列表)是没有意义的。
代码正在做的是等待 promise(s) 解决,执行一些逻辑,并将结果数据设置到范围 属性。
有人可以向我解释这段代码的作用吗?我知道它获取国家并将它们推送到网页中显示的列表中,但为什么呢?我认为 $scope.countries = service.query() 就足够了还是这种方式可以避免异步问题?
$q.all([$scope.address.$promise, $scope.countrys.$promise]).then(function() {
if (!$scope.address.country.id) {
return $q.reject();
}
return Country.get({id : $scope.address.country.id}).$promise;
}).then(function(country) {
$scope.countrys.push(country);
});
代码注释中的说明。这是使用 promise 机制的有条件数据加载过程。如果对您来说还不够,请尝试更详细地说明您的问题
// if address and countries was loaded (probably from ajax request)
$q.all([$scope.address.$promise, $scope.countrys.$promise]).then(function() {
// if address doesn't exist reject all actions
if (!$scope.address.country.id) {
return $q.reject();
}
// otherwise load country based on address field as a promise
return Country.get({id : $scope.address.country.id}).$promise;
}).then(function(country) {
// when loading process is finished add country to dataset
$scope.countrys.push(country);
});
$q.all([promise1, promise2, ...])
Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
service.query()
必然会return一个promise,在异步调用完成时解析。使用 promise 设置范围 属性(毫无疑问,您将绑定到某种形式的列表)是没有意义的。
代码正在做的是等待 promise(s) 解决,执行一些逻辑,并将结果数据设置到范围 属性。