【问题标题】:Axios Retry for success response interceptorAxios 重试成功响应拦截器
【发布时间】:2020-11-21 12:23:17
【问题描述】:

如果 API 响应的状态码在指定时间后为 202,我想重试请求。

在 axios 成功拦截器中,我是这样做的

    function axiosRetrySuccessInterceptor(response) {
         const { status, config } = response;
         // Retry the request on http status code 202
         if (status === 202 ) {

            return new Promise(() => {

               setTimeout(() => {

                  axios.request(config)

                }, 2000);
            });

         } else {

            // No need to do anything, take rest
            return Promise.resolve(response);
         }
    }

     
    // calling function
    axios.interceptors.response.use(axiosRetrySuccessInterceptor,axiosRetryInterceptor);

如果有其他非 202 API 调用,我想清除之前的重试请求。

我也添加了 clearTimeout 但没有成功。

当我返回上一个屏幕时,会调用新的 API,但仍会调用以前的重试 API。它不会停止。 也使用 clearTimeout 尝试过类似下面的操作,但没有成功,而是停止重试

     var retry = setTimeout(() => {

        axios.request(config)

        clearTimeout(retry)
     })

【问题讨论】:

    标签: javascript api axios interceptor axios-retry


    【解决方案1】:

    问题是你没有解决你内心的承诺吗?

      function axiosRetrySuccessInterceptor(response) {
             const { status, data, config } = response;
             // Retry the request on http status code 202
             if (status === 202 ) {
    
                return new Promise((resolve) => {
    
                   setTimeout(() => {
    
                      axios.request(config).then(resolve);
    
                    }, data.retryAfter);
                });
    
             } else {
    
                // No need to do anything, take rest
                return Promise.resolve(response);
             }
        }
    
    

    【讨论】:

    • 这种方式也试过了,但也不会停止返回的重试
    • 我不确定您所说的“停止重试返回”是什么意思
    • 如果有其他 API 调用,我想停止之前的重试请求
    • 请求一旦发生就无法停止。
    • 如果新的请求不是202,它应该停止重试。对吗?
    【解决方案2】:
    return new Promise(resolve => {
                    const abc = setTimeout(() => {
                        axios.request(config).then(resolve);
                        clearTimeout(abc);
                    }, data.retryAfter);
                });
    

    @TKol 试过了,但是没用

    【讨论】:

      猜你喜欢
      • 2021-08-06
      • 2022-01-25
      • 2020-09-25
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多