I have a problem with reading the variable from a file, which changes it with the promise function.
I have two modules:
Example
config.js
// some imports
let currentMacAddress;
(async () => {
currentMacAddress = await toMAC(cameraIp);
console.log(currentMacAddress) // works, sets mac address as expected
})();
module.exports = {
currentMacAddress,
}
somefile.js
const { currentMacAddress } = require('./config.js')
console.log(currentMacAddress) // undefined
setTimeout(() => console.log(currentMacAddress), 10000) // undefined, the timeout is enough for this operation
I believe this is because require
does import only one time, so it sets the variable with the value of currentMacAddress
which is undefined
and that's it.
How can I persist the value in currentMacAddress
so that any other module could access its updated value?
Make the currentMacAddress
a property of the exported object:
const config = {currentMacAddress: undefined};
(async () => {
config.currentMacAddress = await toMAC(cameraIp);
})();
module.exports = config;
And import it without deconstructing:
const config = require('./config.js')
console.log(config.currentMacAddress)
setTimeout(() => console.log(config.currentMacAddress), 10000)