【发布时间】:2020-03-27 12:23:48
【问题描述】:
我有多个 JSON 要加载,并且必须检查它们是否都被正确提取。所以我使用 Promise.all 来等待所有的fetch。
第一个 valid.json 存在,而不是第二个,所以第二个 fetch 以 404 结尾。
但是尽管有Promise.reject,Promise.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 ]
(当然检查了所有类似的问题,但没有任何帮助????)
edit - 在以下答案后修复代码:
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;
});
【问题讨论】:
标签: javascript promise fetch