【问题标题】:Angular call two promises in chain with the result of the firtsAngular 调用链中的两个 Promise,结果是第一个
【发布时间】:2015-07-24 22:13:56
【问题描述】:

我仍然在使用 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 都不能这样工作。互联网上的大多数教程/文章也解释了如何一个接一个地链接调用,但我找不到任何解释如何像我需要的那样链接它们。

【问题讨论】:

    标签: javascript ajax angularjs angular-promise


    【解决方案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 
       });
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      • 2013-10-18
      • 2019-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多