Sisir Sisir - 2 years ago 170
Ajax Question

Axios Request Interceptor wait until ajax call finishes

I have an request interceptor for axios calls. It checks my jwt token and call for refresh if necessary.

axios.interceptors.request.use((config) =>{

const state = store.getState(); // get renewed state
const time = Math.floor( new Date().getTime() / 1000 );

&& time >= state.jwt.expires - 120
&& state.jwt.refresh_before > time
){ // expiring in 2 min. refresh

//dispatch({type: 'JWT_REFRESH_REQUEST'});
axios.get( API_BASE_URL + '/auth/refresh')
// dispatch({type: 'JWT_REFRESH_SUCCESS', payload:});
axios(config).then(resolve, reject);


return config;

This code calls the refresh correctly and saves the new token but the original call doesn't holds until the interceptor request is done, so the expired token is used.

So, I guess I need to make synchronous call from interceptor.

Answer Source

Avoid synchronous calls for HTTP requests, as they just make your application hang.

What you need to do here is make the calling code asynchronous - the general rule with anything callback, promise or async related is that once you are async everything needs to be async.

Here, axios.get returns a Promise - an object that keeps track of the asynchronous HTTP request and resolves once it has finished. You need to return that, rather than the config.

We do that by returning a new Promise - if an HTTP request for a new token is required it waits for it, if no it can resolve immediately.

axios.interceptors.request.use(config =>
    new Promise((resolve, reject) => {
        // ... your code ...

        axios.get( API_BASE_URL + '/auth/refresh')
            .then(response => {
                // Get your config from the response
                const newConfig = getConfigFromResponse(response);

                // Resolve the promise
            }, reject);

        // Or when you don't need an HTTP request just resolve

Whenever you see that then you're dealing with Promise, and once you are everything needs to return a Promise.

This is much easier if you can use async/await - new keywords supported by modern browsers and transpilable if you need to support legacy users. With these you can just put the Promise call inline with the await keyword.

axios.interceptors.request.use(async config =>

    // ... your code ...

    if(/* We need to get the async token */) {
        const response = await axios.get( API_BASE_URL + '/auth/refresh');
        config = getConfigFromResponse(response);

    return config;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download