Axios Request Interceptor wait until ajax call finishes
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 resolve(newConfig); }, reject); // Or when you don't need an HTTP request just resolve resolve(config); })});
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;});