2π
Is it possible to skip all subsequent
.then(...)
and.catch(...)
calls within one of such handlers to go directly to.finally()
?
Currenly I stop the chain by just infinitely waiting β yet this approach of pending Promise is an obstacle.
Indeed, donβt do that. You can skip then
handlers by using rejections (exceptions) for flow control, but the more appropriate way is to handle this by nesting the part of the chain to be skipped inside an if
statement.
This is done to handle certain API responses that have common response handling (like responses with code >= 500)
For that, you should use something like
return axios.request(endpoint).then(response => {
β¦
}).catch(error => {
if (api.handleCommonError(error)) return; // returns false if it couldn't handle the error
β¦
}).finally(() => {
β¦
});
Yes, you cannot hide this kind of error handling inside an api.request
function.
1π
You can use async
and await
. All modern browsers support them, and your bundler can make them compatible with older browsers.
For example:
async function request (endpoint) {
try {
const response = await axios.request(endpoint);
return api.onSuccess(response);
} catch (err) {
api.onError(err);
} finally {
// Always executed, even if no error was thrown
}
}
You can also do it more traditionally:
function request (endpoint) {
return axios.request(endpoint).then(api.onSuccess, api.onError).then(() => {
// Code is always executed after error / success
}
}