Eu tenho vários JSON para carga e deve verificar se todos eles estão bem improvável. Então eu uso um Promise.all que esperar por toda a fetch
.
O primeiro valid.json
existe, não o segundo, então o segundo fetch
termina com um 404. Mas, apesar da Promise.reject
, Promise.all
ainda registra Success!
em vez de jogar o último erro.
Existe algo que eu perdi sobre como Promise.all
funciona?
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 ]
(Verificado todas as perguntas semelhantes é claro, mas nada ajudou 😕)
Código fixo depois abaixo respostas - 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;
});