简体   繁体   中英

Changing variable value in module with async function and than importing in other one

I have a problem with reading the variable from a file, which changes it with the promise function.

I have two modules:

  • one that exposes configuration, and obtains mac address from the device, the app is running on
  • one that consumes the configuration

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)

Export the async function from config.js

config.js

const some = async () => {
  await timeout(3000);
  currentMacAddress = "some value";
  return currentMacAddress;
};

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

module.exports = some;

Now in other file

somefile.js

import like this

const some = require("./config.js");

const start = async () => {
  const currentMacAddress = await some();
  console.log(currentMacAddress);
};
start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM