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

时间:2022-05-16 19:39:57

I'm still having troubles with Angular promises. I have three factories: getPosition, which obviously gets current position, geoCode, which uses google's reverse geocoding to get the name of the city, and getData, which gets some data from API depending on the position. I need to call geoCode and getData right after I get the position. I managed to chain getPosition and geoCode like this:

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

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);
    });

How do I add the call to getData into the chain so that it is called with the data of the first call to? I tried something like this :

如何将对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);
   });

But both geoCoding and getData don't work this way. Also most tutorials/ articles on the internet explain how to chain calls one after another, but I couldn't find anything explaining how to chain them like i need.

但geoCoding和getData都不能以这种方式工作。互联网上的大多数教程/文章也解释了如何一个接一个地连接呼叫,但我找不到任何解释如何链接它们的东西,就像我需要的那样。

1 个解决方案

#1


1  

have you tried like this:

你试过这样的:

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 
   });

It's just a principle, but you get the point.

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

#1


1  

have you tried like this:

你试过这样的:

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 
   });

It's just a principle, but you get the point.

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