Si vous avez trois points finaux différents qui ne sont pas dépendants les uns des autres, vous pouvez utiliser cette approche :
export async function handleResponse(response) {
if (response.ok) return response.json();
if (response.status === 400) {
const error = await response.text();
throw new Error(error);
}
throw new Error("Network response was not ok.");
}
export function handleError(error) {
console.error("API failed. " + error);
throw error;
}
export function GetCountries() {
const url = "/countries"
return fetch(url, {
method: "GET",
credentials: "include",
}).then(handleResponse).catch(handleError);
}
export function GetCities() {
const url = "/cities"
return fetch(url, {
method: "GET",
credentials: "include",
}).then(handleResponse).catch(handleError);
}
export function GetRegions() {
const url = "/regions"
return fetch(url, {
method: "GET",
credentials: "include",
}).then(handleResponse).catch(handleError);
}
function getAddressStructure() {
return Promise.all([
GetCountries(),
GetCities(),
GetRegions()
])
.then((response) => {
return {
countries: response[0],
cities: response[1],
regions: response[2]
};
})
.catch((error) => {
return {
countries: response[],
cities: response[],
regions: response[]
}
});
}
// this is how you can use it:
getAddressStructure()
.then((response) => {
var apiResults = { };
apiResults = { ...response};
return resolve(apiResults);
})