AggregateError: Promise.any 中没有 Promise 被解决
当传递给 Promise.any()
的所有 Promise 都被拒绝时,就会发生 JavaScript 异常“No Promise in Promise.any was resolved”。这是 AggregateError
的唯一内置用法。
消息
AggregateError: All promises were rejected (V8-based) AggregateError: No Promise in Promise.any was resolved (Firefox) AggregateError (Safari)
错误类型
哪里出错了?
Promise.any()
仅在传递给它的所有 Promise 都被拒绝时才会被拒绝。您应该访问 errors
以获取拒绝原因的数组。有关如何处理异步拒绝的 Promise 的更多信息,请参阅 使用 Promise。当 Promise.any()
接收一个空的可迭代对象时,也会引发此错误。
示例
空可迭代对象
js
Promise.any([]).catch((error) => {
console.error(error); // AggregateError: No Promise in Promise.any was resolved
});
处理所有拒绝
js
const promises = [
fetch("/data-location1"),
fetch("/data-location1"),
fetch("/data-location1"),
];
Promise.any(promises)
.then((value) => console.log(value))
.catch((error) => {
// None of the fetches were successful
for (const e of error.errors) {
console.error(e);
}
});
// Using await
async function fetchFirstSuccessful() {
try {
const value = await Promise.any(promises);
console.log(value);
} catch (error) {
for (const e of error.errors) {
console.error(e);
}
}
}