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

Node.js中如何在异步jsonReader外正确获取全局变量值?

问题解决:异步回调中变量赋值后外部获取undefined

核心问题

jsonReader是异步函数,它的回调逻辑会在文件读取完成后才执行;而你后面的doc.render()是同步执行的——也就是说,doc.render()运行时,myaddress还没被回调函数赋值,自然会显示undefined。

另外你的代码还有两个小错误:

  • data.records的data字段里是address,不是property_name,原代码的map逻辑拿不到值;
  • forEach循环会把myaddress依次覆盖为每个地址,最终只会保留最后一个地址(DEF 456 Street),如果只需要单个地址,没必要用forEach遍历赋值。

解决方案

方案1:把渲染逻辑放到异步回调内部(最直接)

直接在jsonReader的回调里完成地址取值,然后调用doc.render(),确保拿到值后再执行渲染:

var myaddress;
jsonReader('./data.json',(error,data)=>{
    if(error){
        console.log(error);
        return; // 出错时终止后续逻辑
    }
    // 修正属性名:读取data.address而不是property_name
    const addresses = data.records.map(record => record.data.address);
    // 按需取地址:比如取第一个
    myaddress = addresses[0];
    // 如果需要遍历所有地址并逐个渲染,就把doc.render放到forEach里
    // addresses.forEach(address => {
    //     doc.render({
    //         propertyname: address,
    //         propetytype: "",
    //         phone: "",
    //         description: "New Website",
    //     });
    // });
    doc.render({
        propertyname: myaddress,
        propetytype: "",
        phone: "",
        description: "New Website",
    });
})

方案2:用Async/Await封装(更优雅的异步处理)

把jsonReader包装成Promise,再用async/await把异步逻辑写成同步风格:

// 先把jsonReader封装为返回Promise的函数
function readJson(path) {
    return new Promise((resolve, reject) => {
        jsonReader(path, (error, data) => {
            error ? reject(error) : resolve(data);
        });
    });
}

// 用async函数处理异步逻辑
async function renderDoc() {
    try {
        const data = await readJson('./data.json');
        const addresses = data.records.map(record => record.data.address);
        const myaddress = addresses[0]; // 按需选择地址
        doc.render({
            propertyname: myaddress,
            propetytype: "",
            phone: "",
            description: "New Website",
        });
    } catch (error) {
        console.log(error);
    }
}

// 执行渲染函数
renderDoc();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 21:35:25