【发布时间】:2014-09-24 12:34:00
【问题描述】:
如何在 AngularJS 中创建 2 个同时异步请求,其中一个操作必须在第一个请求之后完成?
我想做这样的事情:
- 调用第一个 Web 服务(接收 x)
- 调用第二个 Web 服务(接收 y)
- 在我收到来自第一个 Web 服务 (f(x)) 的响应后做一些事情
- 在我拥有两个数据 (g(x,y)) 后做一些事情
以下做法:
$q.all({
x: $http.get('http://resourceX'),
y: $http.get('http://resourceY')
}).then(function(results) {
$scope.a = f(results.x.data); // where to place this line ?
$scope.z = g(results.x.data, results.y.data);
});
不是高效,因为即使收到了resourceX,它也在等待resourceY。
我想在 x 可用时调用函数 f,并在 x 和 y 可用时调用函数 g。
我想要的伪代码如下所示:
$q.all({
x: $http.get('http://resourceX'),
y: $http.get('http://resourceY')
}).when(x is ready) {
$scope.a = f(results.x.data);
}).then(function(results) {
$scope.z = g(results.x.data, results.y.data);
});
所以,我希望在 $q.all 方法 和
之间实现性能组合$http.get('http://resourceX').success(function(x) {
$scope.a = f(x);
$http.get('http://resourceY').succes(function(y){
$scope.z = g(x, y);
});
});
【问题讨论】:
标签: javascript angularjs asynchronous xmlhttprequest simultaneous