Angular将这两个承诺与第一个结果联系在一起

时间:2015-07-24 14:03:26

标签: javascript ajax angularjs angular-promise

我仍然遇到Angular承诺的麻烦。我有三个工厂:getPosition,它显然是当前位置,geoCode,它使用谷歌的反向地理编码来获取城市的名称,getData,它得到了一些来自API的数据取决于位置。我得到职位后,我需要立即致电geoCodegetData。我设法链接getPositiongeoCode,如下所示:

getPosition.get().then(function(geoInfo){
      $scope.$storage.geoInfo = geoInfo;
      return geoCoding.getFromObj(geoInfo).then(function(city){
        $scope.$storage.city = city;
        $scope.city = $scope.$storage.city;
      },function(reason){
        alert("Geocoding error: " + reason);
      })
    }, function(reason){
      alert("Location error: " + reason);
    });

如何将对getData的调用添加到链中,以便使用第一次调用的数据调用?我试过这样的事情:

getPosition.get().then(function(geoInfo){
      $scope.$storage.geoInfo = geoInfo;
      return  function(geoInfo){
        geoCoding.getFromObj(geoInfo).then(function(city){
        $scope.$storage.city = city;
        $scope.city = $scope.$storage.city;
      },function(reason){
        alert("Geocoding error: " + reason);
      });
        getData.getFromObj(geoInfo).then(function(data){
          $scope.$storage.data=data;
        })
      }
    }, function(reason){
      alert("Location error: " + reason);
   });

geoCodinggetData都不会这样做。互联网上的大多数教程/文章也解释了如何一个接一个地连接电话,但我找不到任何解释如何将它们链接起来的东西。

1 个答案:

答案 0 :(得分:1)

你试过这样的尝试:

getPosition()
  .then(function(pos){
     return getGeoCoding(pos); // should return promise
   })
  .then(function(geo){
     return getData(geo); // should return promise
   })
  .then(function(data){
     // do stuff with data
   })
  .catch(function(err){  // falls to this if any of the above fails
    //console err 
   });

这只是一个原则,但你明白了。