I am making external API calls in my Firebase Cloud Functions in which I need to pass an authentication token. Instead of generating a new authentication token every time I need to make the external API call, I store the API token when I don't have one, and as long as it's valid, I want to re-use it for further requests.
I have created a global variable globalToken
for this purpose. However, when I call my function to retrieve a token and re-use if possible, an existing token is never re-used as the function always seems to say that the global variable is set to null.
let globalToken = null
async function getToken() {
if(!!globalToken) {
console.log('was able to re-use already-existing token')
return globalToken
}
console.log(`no existing token could have been reused because globalToken was set to: ${globalToken}`) // always displays globalToken as null
const newToken = axios.post(...)
globalToken = newToken
console.log(`updated globalToken to: ${globalToken}`) // correctly prints out the new token
return newToken
}
exports.getToken = functions.https.onCall(async (data, context) => {
const token = await getToken()
return ({ token: token })
})
If the logs confirm that the global variable is being changed at the time of new token retrieval, why do the subsequent runs read the global variable as null
value instead of the already-retrieved token?