I have a function named request
:
function request (endpoint) {
return axios.request(endpoint).then(api.onSuccess).catch(api.onError)
}
api.onSuccess
:
onSuccess (response) {
let breakChain = false
... adding some logic here ...
return breakChain ? (new Promise(() => {})) : response
}
api.onError
:
onError (error) {
let breakChain = false
... implementing certain logic here ...
if (breakChain) {
return new Promise(() => {})
} else {
throw error
}
}
api
includes various functions representing different API calls depending on endpoint data, and returns request(endpoint)
.
Currently, I have the code snippet above that returns a Promise with an empty executor always in a pending state to halt subsequent .then(...)
and .catch(...)
executions, as these handlers are constantly waiting for that Promise to settle. This is specifically used to handle certain API responses with common error handling needs (such as responses with status codes >= 500).
The issue now is that I require a call to .finally()
(similar to Vue cookbook - https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#Dealing-with-Errors) to reset a component's state whether there was an error or not, but this continuous pending Promise approach is posing an obstacle.
The question at hand: Is it feasible to bypass all subsequent .then(...)
and .catch(...)
calls within one of these handlers and directly proceed to .finally()
?
Update: It should be noted that both api.onSuccess
and api.onError
serve as fundamental handlers. In other components of the application, additional handlers are appended to the end of the basic chain shown in the request
function. The typical chain structure for an API call looks something like this:
return axios.request(endpoint).then(api.onSuccess).catch(api.onError).then((response) => {...}).catch(() => {...}).finally(() => {...})
(sometimes missing either .finally()
or .catch(...)
block)