I need to call an async function to get my auth token. In an export, I want to include the returned value from this fn.
My first try:
const token = await sessionHandler.getToken();
export const httpService = axios.create({
...
headers: {
"auth-token": token
...
}
});
Of course this doesn't work because the await
is not in a async function.
So I could just wrap this in an async function, right? No, because I'd have to use callbacks. Then again I wouldn't have the export on top-level which doesn't work either.
What's the best way to approach this?
If httpService
must not be async then I would use interceptors
for this kind of requirement, if the token is not ready at the first request, then then the interceptor will wait until the promise is fulfilled. The token will be requested only once.
const axios = require('axios')
const token = sessionHandler.getToken();
export const httpService = axios.create({
...
headers: {
...
}
});
httpService.interceptors.request.use(function(config) {
return token.then(token => {
config.headers['auth-token'] = token;
return config;
})
}, function(error) {
console.dir(error)
// Do something with request error
return Promise.reject(error);
});
EDIT Personally I prefer if data is only requested on demand and not on include so I would use a slightly different version:
const axios = require('axios')
let token;
export const httpService = axios.create({
...
headers: {
...
}
});
httpService.interceptors.request.use(function(config) {
token = token || sessionHandler.getToken(); //request it only if not already requested.
return token.then(token => {
config.headers['auth-token'] = token;
return config;
})
}, function(error) {
console.dir(error)
// Do something with request error
return Promise.reject(error);
});