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

Time:12-18

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?

CodePudding user response:

Make the currentMacAddress a property of the exported object:

const config = {currentMacAddress: undefined};
(async () => {
  config.currentMacAddress = await toMAC(cameraIp);
})();
module.exports = config;

CodePudding user response:

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();
  • Related