У меня есть несколько 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 ]
(Проверено все подобные вопросы, конечно, но ничего не помогало 😕)
редактировать - Исправлен код после того, как ниже ответов:
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;
});