Search code examples
javascriptregedit

Value of a variable to be read asynchronously


I read value from registry and set value from registry to variable in my code. I see fetching the value from registry is happening asynchronously.

I am regedit package from node. I have tried setTimeout for constructENVTable, but it didn't work. Please note:mainfunc() is triggered from html page body onload

//declared globally
var regValue = "";

function mainfunc() {
  setRegistryValueForFirstTime();
  constructENVTable();
}

function setRegistryValueForFirstTime() {
  let path = "HKLM\\....\\Environment";
  regedit.list('HKLM\\...\\Environment', function(err, result) {
    try {
      regValue = result[path].values.XYZ.value;
      alert(regValue); //prints value correctly
      app.console.log("Registry value for ANSYS_LI is  already set");
    } catch (err) {
      app.console.log(err);
      app.console.log("setting up registry value");
      setRegistryValue();
    }
    alert(regValue); //doesn't print value
  });
}

  function constructENVTable() {
    alert(regValue); //doesn't print value
  }


Solution

  • You can wrap regValue with a Promise:

    var regValue;
    
    function mainfunc() {
        setRegistryValueForFirstTime();
        constructENVTable();
    }
    
    function setRegistryValueForFirstTime() {
        let path = "HKLM\\....\\Environment";
        regedit.list('HKLM\\...\\Environment', function (err, result) {
            try {
                regValue = new Promise(
                    (resolve, reject) => resolve(result[path].values.XYZ.value)
                )
    
                app.console.log("Registry value for ANSYS_LI is  already set");
            } catch (err) {
                app.console.log(err);
                app.console.log("setting up registry value");
                setRegistryValue();
            }
            alert(regValue); //doesn't print value
        });
    }
    
    function constructENVTable() {
        // alert(regValue); //doesn't print value
        regValue.then(
            value => alert(value)
        )
    }