Лучший способ использования fetch, который я знаю, заключается в следующем:
const displayCharacters = async () => {
if(filteredCharacters !== 'default'){
const a = filteredCharacters.map(e => e.name);
const options = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ 'data' : a })
};
const b = await fetch("/image",options)
.then(res => {
// Handle API Errors
if (!res.ok) {
throw Error(res.statusText);
}
// Return if no errors
return res.json();
})
// this is the data you want
.then(data => data)
// it will only reject on network failure or if anything prevented the request from completing
.catch(error => {
console.log(error.message)
});
return b;
}else{
return "yikes";
}
}
По сути, вы цепляете два шага и ловите, чтобы полностью понять ответ - первый, затем проверяет ошибки уровня API - второй затем получает данные - вызов вызывается в случае, если он не может получить доступ к API непосредственно, как проблемы с подключением