Axios Retry for success response interceptor

1.2k Views Asked by At

I have situation where I want to retry the request if status code for API response is 202 after the specified time.

In axios success interceptor, I am doing like

    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);

I want to clear the previous retry request if any other non 202 API calls.

I have added the clearTimeout as well but no success.

When I go back the previous screen, new API is called and but previous retry API still called. It doesn't stop. Have tried something like below also using clearTimeout, but no success, instead it stop the retry

     var retry = setTimeout(() => {

        axios.request(config)

        clearTimeout(retry)
     })
2

There are 2 best solutions below

0
On
return new Promise(resolve => {
                const abc = setTimeout(() => {
                    axios.request(config).then(resolve);
                    clearTimeout(abc);
                }, data.retryAfter);
            });

@TKol Have tried this but didn't work

7
On

Is the problem that you're not resolving your inner promise?

  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);
         }
    }