0
var cachekey = null;

function redis_post(req, res, next) {
    client.get(keyName, (err, redis_data) => {
        if (err) {
            throw err;
        }
        else if (!redis_data) {
            client.set(keyName, JSON.stringify(key));
            cachekey = JSON.parse(redis_data);
        } else if (redis_data) {
            cachekey = JSON.parse(redis_data);
        }
        // next()
    })
    // console.log("check"+cachekey) // undefined
}
const axiosInstance = axios.create({
    baseURL: process.env.API_BASE_URL,
    headers: {
        'Content-type': 'application/json',
        'accept': 'application/json',
        'Authorization': cachekey // undefined
    },
    credentials: true
});

the problem was simple async await query, I just put async before redis_post func and await before client.get(key....)

  • **IF** `redis_post` / `client.get` is being called, this should work as expected. I don't think that this problem has to do with hoisting. – LeoDog896 Feb 05 '23 at 13:31
  • No, it has nothing to do with hoisting. It's about the order of execution with asynchronous callbacks. – Bergi Feb 05 '23 at 14:36

2 Answers2

0

The problem is that you are doing some async code and depnding on it you assign a value. Console.log is called before you got the response fom the async function.

The link in the comment section from jabaa refers to this problem.

Alexandr
  • 16
  • 1
-1

We use Interceptors in axios instance maybe it solve your problem

const axiosInstance = axios.create({
    baseURL: process.env.API_BASE_URL,
    headers: {
        'Content-type': 'application/json',
        'accept': 'application/json',
        'Authorization': cachekey // undefined
    },
    credentials: true
});

axiosInstance.interceptors.request.use(function (config) {
    // Do something before request is sent
    config.headers.Authorization =  cachekey;
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });