How to break promise chain?
instance.interceptors.response.use((response) ->
# my server returns {"status": "success", "data": ...}
# or {"status": "fail", "data": ...}
server_response = response.data
if server_response.status == 'fail'
alert(server_response.data) # global alert when status == 'fail'
# this will throw a "> Uncaught (in promise) ..."
# how can i do to prevent/stop it enter into the next then()?
# only when server_response.status == 'success' enter the `then` function
return Promise.reject(response)
# only status == 'success' will reach here:
return response
# in my button actions
instance
.post('accounts/login', account)
.then (response) ->
# if i don't use Promise.reject() in the interceptors,
# everytime i will use a if:
if response.data.status == 'success'
doThings(response)
# but i want this
doThings(response)
in angular:
http://blog.zeit.io/stop-a-promise-chain-without-using-reject-with-angular-s-q/
in bluebird:
http://openmymind.net/Cancelling-Long-Promise-Chains/
the above examples break chains in then()
, can axios break it also in interceptor, somthing likes:
instance.interceptors.response.use((response) ->
if someCondition(response)
return null # break the chain
else
return response
I don't recommend you doing so, but if you finally want it you can return a never-resolving promise in your interceptors. E.g.:
instance.interceptors.response.use((response) =>聽{
if (someCondition(response) {
return new Promise(() => {});
}
return response;
});
I didn't like the idea of using a promise that never resolves or rejects, so I opted to use bluebird's cancellation to do something like this:
axios.interceptors.response.use(null, error => {
let promise = new Promise(resolve, reject) => {
setTimeout(() => {
<code>
promise.cancel()
})
})
return promise
})
the setTimeout allows the promise to initalize itself so that a proper promise is still returned from the interceptor and .cancel()
can be called after the fact
Reply to @rubennorte:
I don't recommend you doing so, but if you finally want it you can return a never-resolving promise in your interceptors. E.g.:
instance.interceptors.response.use((response) => { if (someCondition(response) { return new Promise(() => {}); } return response; });
https://stackoverflow.com/a/20068922
In short - at least in modern browsers - you don't have to worry about unresolved promises as long as you don't have external references to them
Most helpful comment
I don't recommend you doing so, but if you finally want it you can return a never-resolving promise in your interceptors. E.g.: