You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在函数内为全局变量赋值?异步场景下赋值异常解决

异步Redis调用导致全局变量赋值延迟,axios实例无法获取有效值的解决方案

我定义了全局变量cachekey,在redis_post函数中通过Redis的client.get异步回调尝试为其赋值,但后续创建axiosInstance时发现cachekey始终为undefined。

相关代码如下:

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
});

问题根源

核心是异步执行顺序问题:client.get属于异步IO操作,它的回调函数要等Redis返回结果后才会触发,但代码会先同步执行axios.create创建实例,此时cachekey还未被回调赋值,所以是undefined。

解决方案

通过async/await将异步调用转为同步执行逻辑,确保cachekey完成赋值后再进行后续操作。修改后的代码如下:

var cachekey = null;

async function redis_post(req, res, next) {
    try {
        const redis_data = await client.get(keyName);
        if (!redis_data) {
            await client.set(keyName, JSON.stringify(key));
            // 原代码此处JSON.parse(redis_data)会报错(redis_data为null),直接用key赋值更合理
            cachekey = key;
        } else {
            cachekey = JSON.parse(redis_data);
        }
        // next()
    } catch (err) {
        throw err;
    }
}

// 建议在redis_post执行完成后再创建axios实例,保证拿到最新的cachekey
async function initAxiosInstance() {
    await redis_post(req, res, next); // 需传入正确的req/res/next,或单独抽离获取cachekey的逻辑
    return axios.create({
        baseURL: process.env.API_BASE_URL,
        headers: {
            'Content-type': 'application/json',
            'accept': 'application/json',
            'Authorization': cachekey
        },
        credentials: true
    });
}

// 使用时调用initAxiosInstance()获取实例

内容的提问来源于stack exchange,提问作者jaidevsairwa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 16:16:05