Axios: 如何打破拦截器中的承诺链?

创建于 2017-02-19  ·  3评论  ·  资料来源: axios/axios

如何打破承诺链?

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)

角度:
http://blog.zeit.io/stop-a-promise-chain-without-using-reject-with-angular-sq/

在蓝鸟中:
http://openmymind.net/Cancelling-Long-Promise-Chains/

上面的例子打破了then()链,axios 也可以在拦截器中打破它,比如:

instance.interceptors.response.use((response) ->
    if someCondition(response)
        return null  # break the chain
    else
        return response

最有用的评论

我不建议你这样做,但如果你最终想要它,你可以在你的拦截器中返回一个永不解决的承诺。 例如:

instance.interceptors.response.use((response) => {
  if (someCondition(response) {
    return new Promise(() => {});
  }
  return response;
});

所有3条评论

我不建议你这样做,但如果你最终想要它,你可以在你的拦截器中返回一个永不解决的承诺。 例如:

instance.interceptors.response.use((response) => {
  if (someCondition(response) {
    return new Promise(() => {});
  }
  return response;
});

我不喜欢使用永远不会解决或拒绝的承诺的想法,所以我选择使用 bluebird 的取消来做这样的事情:

axios.interceptors.response.use(null, error => {
    let promise = new Promise(resolve, reject) => {
        setTimeout(() => {
            <code>
            promise.cancel()
        })
    })
    return promise
})

setTimeout 允许承诺初始化自己,以便仍然从拦截器返回正确的承诺,并且可以在事后调用.cancel()

回复@rubennorte :

我不建议你这样做,但如果你最终想要它,你可以在你的拦截器中返回一个永不解决的承诺。 例如:

instance.interceptors.response.use((response) => {
  if (someCondition(response) {
    return new Promise(() => {});
  }
  return response;
});

https://stackoverflow.com/a/20068922

简而言之 - 至少在现代浏览器中 - 只要您没有对它们的外部引用,您就不必担心未解决的承诺

此页面是否有帮助?
0 / 5 - 0 等级