gpt4 book ai didi

javascript - Promise.all 中获取失败,未捕获错误

转载 作者:行者123 更新时间:2023-11-30 09:10:52 24 4
gpt4 key购买 nike

我有多个 JSON 需要加载,必须检查它们是否都已正确获取。所以我使用 Promise.all 来等待所有 fetch

第一个 valid.json 存在,第二个不存在,因此第二个 fetch 以 404 结束。但尽管有 Promise.rejectPromise.all 仍然记录 Success! 而不是抛出最后一个错误。

关于 Promise.all 的工作原理,我是否遗漏了什么?

const json_pathes = [
'valid.json',
'not_valid.json'
];

function check_errors(response) {
if (!response.ok) {
Promise.reject('Error while fetching data');
throw Error(response.statusText + ' (' + response.url + ')');
}
return response;
}

Promise.all(json_pathes.map(url =>
fetch(url)
.then(check_errors)
.then(response => response.json())
.catch(error => console.log(error))
))
.then(data => {
console.log('Success!', data);
})
.catch(reason => {
throw Error(reason);
});

// Console:
// Error: "Not Found (not_valid.json)"
// uncaught exception: Error while fetching data
// Array [ […], undefined ]

(当然检查了所有类似的问题,但没有任何帮助😕)


编辑 - 修复以下答案后的代码:

const json_pathes = […]
Promise.all(json_pathes.map(url =>
fetch(url)
.then(response => {
if (!response.ok)
throw Error(response.statusText + ' (' + response.url + ')');
return response;
})
.then(response => response.json())
.catch(error => {
throw error;
})
))
.then(data => {
// Success
})
.catch(error => {
throw error;
});

最佳答案

此调用:

 .catch(error => console.log(error))

...将返回一个已履行的 promise ,而不是一个被拒绝的 promise 。每当您处理拒绝并且希望它作为拒绝冒泡时,您应该明确地这样做:

 .catch(error => {
console.log(error);
throw error; // cascade...
})

顺便说一句,这根本没有效果

 Promise.reject('Error while fetching data');

...因为您没有对这个新创建的、被拒绝的 promise 执行任何操作。

关于javascript - Promise.all 中获取失败,未捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59146553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com