每当您使用.then
时,您基本上都会根据之前的承诺及其状态创建新承诺。你可以利用这个优势(你应该)。
你可以做一些线沿线的:
function getGeolocation() {
return $http.get('/someurl').then(
function resolveHandler(response) {
// $http.X resolves with a HTTP response object.
// The JSON data is on its `data` attribute
var data = response.data;
// Check if the data is valid (with some other function).
// By this, I mean e.g. checking if it is "far from amsterdam",
// as you have described that as a possible error case
if(isValid(data)) {
return data;
}
else {
return null;
}
},
function rejectHandler() {
// Handle the retrieval failure by explicitly returning a value
// from the rejection handler. Null is arbitrarily chosen here because it
// is a falsy value. See the last code snippet for the use of this
return null;
}
);
}
function getData() {
return $http.get('/dataurl').then(...);
}
,然后在两个承诺,这反过来又创造了新的承诺,一旦所有给定的承诺已经解决解决使用$q.all
。
注意:在Kris Kowal's Q,这Angular's $q service是基于,您可以使用allSettled
方法,它确实几乎一样all
,但是当所有的承诺都是解决(履行或拒绝),而不是只解决如果所有的承诺都是履行。 Angular的$ q没有提供这种方法,所以你可以通过显式地使失败的http请求解析来解决这个问题。
,那么你可以这样做:
$q.all([getData(), getGeolocation()])
.then(function(data, geolocation) {
// `data` is the value that getData() resolved with,
// `geolocation` is the value that getGeolocation() resolved with.
// Check the documentation on `$q.all` for this.
if(geolocation) {
// Yay, the geolocation data is available and valid, do something
}
// Handle the rest of the data
});
你的承诺仍然可以'成功resolve'即使数据是“负“或不存在 - 将此视为成功的结果。在'try/catch'块中处理'catch'类似于'catch',并处理致命的异常。 – 2014-11-04 08:01:08
如何查看餐厅数据后是否解决了地理承诺问题。如果它没有解决,我不会等待它(因为结果可能是该人不在阿姆斯特丹)。 – 2014-11-05 07:36:22
也许我错过了一些东西,但无论您是获取了数据还是得到了否定结果,您都可以解决它。这将是您下一步的输入。 – 2014-11-05 07:39:33