如何在含async函数的模块中更新变量并供其他模块读取?
问题解决:异步更新模块变量后无法在其他模块获取最新值
问题原因
你判断的完全正确:require加载模块时会生成导出对象的副本,currentMacAddress是基本类型,导出时把初始值undefined绑定到了导出对象的属性上。后续异步操作修改的是模块内部的独立变量,并不会同步更新导出对象里的属性,所以其他模块始终只能拿到初始的undefined。
解决方案
方案1:导出获取最新值的函数
把获取MAC地址的逻辑封装成函数,每次调用函数时返回当前最新的变量值:
config.js
// some imports let currentMacAddress; (async () => { currentMacAddress = await toMAC(cameraIp); console.log(currentMacAddress); // 正常输出MAC地址 })(); module.exports = { getCurrentMacAddress: () => currentMacAddress };
somefile.js
const { getCurrentMacAddress } = require('./config.js'); console.log(getCurrentMacAddress()); // 初始为undefined setTimeout(() => console.log(getCurrentMacAddress()), 10000); // 可获取更新后的MAC地址
方案2:导出包含可变属性的对象
导出一个对象,让currentMacAddress作为这个对象的属性。因为对象是引用类型,其他模块引用的是同一个对象,属性更新后会同步反映:
config.js
// some imports const config = { currentMacAddress: undefined }; (async () => { config.currentMacAddress = await toMAC(cameraIp); console.log(config.currentMacAddress); // 正常输出MAC地址 })(); module.exports = config;
somefile.js
const config = require('./config.js'); console.log(config.currentMacAddress); // 初始为undefined setTimeout(() => console.log(config.currentMacAddress), 10000); // 可获取更新后的MAC地址
方案3:直接导出Promise(推荐)
既然获取MAC地址是异步操作,直接导出Promise,让消费模块等待Promise完成后再获取值,避免依赖定时器这种不可靠的方式:
config.js
// some imports const currentMacAddressPromise = toMAC(cameraIp); // 可选:提前打印结果 currentMacAddressPromise.then(mac => console.log(mac)); module.exports = { currentMacAddressPromise };
somefile.js
const { currentMacAddressPromise } = require('./config.js'); // 使用async/await async function init() { const mac = await currentMacAddressPromise; console.log(mac); // 直接拿到最终的MAC地址 } init(); // 或者用then方法 currentMacAddressPromise.then(mac => console.log(mac));
这种方式更符合异步代码的最佳实践,不需要依赖定时器,能确保拿到的是最终的有效MAC地址。
内容的提问来源于stack exchange,提问作者Dmytro Soltusyuk
相关产品推荐
相关产品推荐

