[英]How to process multiple errors from $http.get
我正在通过动态构建URL发出多个GET
请求。
对于任何错误,我想获取response.config.url
的值,对其进行处理,然后将结果值推入一个对象中。
当我仅收到一个错误时,下面的代码工作正常。
当返回多个错误时,只有最后一个错误的值被压入对象。 我猜这是因为它会覆盖以前的代码。
我该如何预防? 出现多个错误时,如何确保所有值都被压入对象?
(注意: annotation
是我从输入字段中获得的字符串数组; _
是lodash)
function checkVariants(annotation) {
var lemmas = annotation.text.split(' ');
var results = [];
var words = [];
for (var i = 0; i < lemmas.length; ++i) {
var urlLemmas = encodeURIComponent(lemmas[i]).toLowerCase();
results.push(urlLemmas);
$http({
method: 'GET',
url: 'https://xxxxxxx.org/variants/' + results[i] + '.txt'
}).then(function successCallback(response) {
console.log('Success: ', response.status)
}, function errorCallback(response) {
var url = response.config.url;
words = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
_.extend(annotation, {
variants: words
});
})
}
}
将您的variants
属性设置为数组,并在其中添加words
:
$http({
method: 'GET',
url: 'https://wwwcoolservice.org/variants/' + results[i] + '.txt'
}).then(function successCallback(response) {
console.log('Success: ', response.status)
}, function errorCallback(response) {
var url = response.config.url;
words = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
if (!annotation.variants || !annotation.variants.length) { // First error: create the array
annotation.variants = [words];
} else { // next errors: add to the array
annotation.variants.push(words);
}
});
使用此解决方案,您需要检测是否已经具有variants
属性,因此在调用_.extend
会增加附加值。
我设法得到了想要的东西。
以下代码仅供参考:
function checkVariants(annotation) {
var lemmas = annotation.text.split(' ');
var results = [];
var oedVars = [];
for (var i = 0; i < lemmas.length; ++i) {
var urlLemmas = encodeURIComponent(lemmas[i]).toLowerCase();
results.push(urlLemmas);
$http({
method: 'GET',
url: 'https://XXXXXX.org/variants/' + results[i] + '.txt'
}).then(function successCallback(response) {
console.log('Success: ', response.status)
}, function errorCallback(response) {
var url = response.config.url;
var words = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("."));
oedVars.push(words);
_.extend(annotation, {
variants: oedVars
});
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.