【问题标题】:Simultaneous asynchronous requests in AngularJS containing inner operationAngularJS 中的同时异步请求包含内部操作
【发布时间】: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


    【解决方案1】:

    你可以这样分开调用:

    var promiseX = $http.get('http://resourceX');
    var promiseY = $http.get('http://resourceY');
    
    promiseX.then(function(result {
        $scope.a = f(result.data);
    });
    
    $q.all({
        x: promiseX,
        y: promiseY
    }).then(function(results) {
        $scope.z = g(results.x.data, results.y.data);
    });
    

    【讨论】:

      【解决方案2】:

      这是一个 plnkr,可以满足您的需求http://plnkr.co/edit/6WER28?p=preview

      function getX() {
          var deferred = $q.defer();
          setTimeout(function() {
            deferred.resolve('X');
          }, 300)
      
          return deferred.promise;
        }
      
        function getY() {
          var deferred = $q.defer();
          setTimeout(function() {
      
            deferred.resolve('Y');
          }, 500);
      
          return deferred.promise;
        }
      
        var promiseX = getX();
        var promiseY = getY();
      
        promiseX.then(function(val) {
          console.log('recevied first one :' + val);
        })
      
        $q.all([promiseX, promiseY]).then(function(valuesFromBothInArray) {
          console.log('received both ' + valuesFromBothInArray);
        })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-06-08
        • 2017-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多