Angular 用第一个的结果在链中调用两个 promise
Angular call two promises in chain with the result of the firts
我在使用 Angular promises 时仍有问题。我有三个工厂:getPosition
,它显然获取当前位置,geoCode
,它使用 google 的反向地理编码来获取城市名称,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);
});
如何将对 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);
});
但是 geoCoding
和 getData
都不是这样工作的。此外,互联网上的大多数教程/文章都解释了如何一个接一个地链接调用,但我找不到任何解释如何按照我的需要链接它们的内容。
你试过这样吗:
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
});
这只是一个原则,但你明白了。
我在使用 Angular promises 时仍有问题。我有三个工厂:getPosition
,它显然获取当前位置,geoCode
,它使用 google 的反向地理编码来获取城市名称,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);
});
如何将对 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);
});
但是 geoCoding
和 getData
都不是这样工作的。此外,互联网上的大多数教程/文章都解释了如何一个接一个地链接调用,但我找不到任何解释如何按照我的需要链接它们的内容。
你试过这样吗:
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
});
这只是一个原则,但你明白了。