如何解决Promise.All失败了,尽管所有承诺都成功解决了
我正在编写一个简单的Javascript脚本,该脚本使用XMLHttpRequest对象来查询API。脚本中有两个主要功能; routeLength(startID,endID);
和getSystemSecurity(systemID);
第一个方法返回一个Promise对象,并在其中进行API调用:
function routeLength (startID,endID) {
return new Promise((resolve,reject) => {
const url = `the request URL`;
const xml = new XMLHttpRequest();
xml.onload = function () {
var systems = this.response.split(',');
const length = systems.length - 1;
var routeSecurity = 2;
var promises = [];
systems.forEach((element) => {
if (element[0] == '[') {
promises.push(
getSystemSecurity(element.substr(1,element.length - 1))
);
}
else if (element[element.length - 1] == ']') {
promises.push(
getSystemSecurity(element.substr(0,element.length - 1))
);
}
else promises.push(getSystemSecurity(element));
});
Promise.all(promises).then((values) => {
values.forEach((v) => {
if (v < routeSecurity) routeSecurity = v;
})
resolve({"jumps":length,"security":routeSecurity});
}).catch((error) => {
reject(error)
});
};
xml.open("GET",url);
xml.send();
})
}
此方法向API发出GET请求,并对结果执行一些逻辑。 'systems'数组包含我检查过的所有系统ID(所有这些ID均有效)(如果需要,请删除括号)。推送到promises数组中的promises调用以下函数:
function getSystemSecurity (systemID) {
return new Promise((resolve,reject) => {
const url = `${API_URL}/universe/systems/${systemID}`;
const xml = new XMLHttpRequest();
xml.onload = function () {
if (this.response.error) reject(this.response.error);
const security = this.response["security_status"];
if (security >= 0.5) resolve(HIGH_SECURITY);
else if (security < 0.5 && security > 0) resolve(LOW_SECURITY);
else if (security < 0) resolve(NULL_SECURITY);
else reject({"error":"Invalid security value " + security});
}
xml.onerror = reject("Error executing XMLHttpRequest with ID " + systemID + xml.statusText + xml.responseText);
xml.open("GET",url);
xml.send();
});
}
当我尝试运行此方法时,可以看到所有正确的请求都在发出,包括对/route/
的初始请求以及/universe/systems/
路由。使用开发人员控制台,我可以看到它们均未失败,并且都具有预期的数据。但是,我被告知第一个诺言失败了:
(index):1 Uncaught (in promise) Error executing XMLHttpRequest with ID 30002659
从错误中可以看到,没有填充xml.statusText和xml.responseText,所以我无法确定正在发生的实际错误。
那么,尽管所有请求都使用200个响应代码,但Promise.all为什么会失败?
解决方法
问题出在这一行:
xml.onerror = reject("Error executing XMLHttpRequest with ID " + systemID + xml.statusText + xml.responseText);
您没有分配事件处理程序,而是当场执行执行!
应该是:
xml.onerror = () => reject("Error executing XMLHttpRequest with ID " + systemID + xml.statusText + xml.responseText);
一般性说明:请使用fetch
API,它非常容易使用,并且可以立即返回一个Promise,这样您就可以摆脱所有这些new Promise
构造
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。