异步读取的变量的值

时间:2019-06-21 16:03:36

标签: javascript regedit

我从代码中读取注册表值,并将值从注册表设置为变量。我看到从注册表中获取值是异步发生的。

我是来自节点的regedit软件包。我为setTimeout尝试了constructENVTable,但是没有用。 请注意:mainfunc()是从html页面正文加载触发的

//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
  }

2 个答案:

答案 0 :(得分:3)

嗯,您可以尝试将regValue包裹在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)
    )
}

答案 1 :(得分:1)

为简单起见,您可以在获取值后立即运行该函数,然后将其传递给第二个函数。

var regValue = "";

function mainfunc() {
  setRegistryValueForFirstTime();
}

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

function constructENVTable(regValue) {
  alert(regValue); // get value here and alert it
}