I have a method returning a promise that either resolves or rejects.
myMethod() {
return new Promise((resolve, reject) => {
axiosClient
.get(endpoint)
.then((response) => {
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
}
Is there a way to return another promise in case this produces an error, calling a backup endpoint?? Something along the lines of:
myMethod() {
return new Promise((resolve, reject) => {
axiosClient
.get(endpoint)
.then((response) => {
resolve(response.data);
})
.catch(() => {
axiosClient
.get(backupEndpoint)
.then((response) => {
resolve(response.data);
})
.catch((error) => {
reject(error);
});
});
});
Edit: if this is a duplicate I have not been able to find something about it that is specific to this point. Could it be because it's a bad practice?
Edit2: thanks for the answers, maybe I should clarify better the flow I want to achieve:
get endpoint -> (if this fails) get fallback endpoint -> (if this fails aswell) reject the entire promise
From the above, one could simplify it doing with re-usability best practices, as follows:
myMethod() {
const PromiseHandler = url => {
/**
* this function recevies url
* makes the request and return
* a reposne form the end point
*/
return axiosclient.get(url).then(res => res.data)
}
return PromiseHandler(endpoint)
.catch(() => {
return PromiseHandler(backupEndPoint)
}