简体   繁体   English

无法使用 nodejs 导出访问变量值?

[英]Unable to access Variable value using nodejs exports?

Hey i have fallen into a situation where i cannot access a variable which i have set within a nodejs module which i have exposed with module exports to access from the main file, i will show you below:嘿,我陷入了一种情况,我无法访问我在 nodejs 模块中设置的变量,我已经通过模块导出公开了从主文件访问的变量,我将在下面向您展示:

Login.js :登录.js

let DEVICES;
function a() {
  return DEVICES;
}

async function init() {
  try {
    const __devices = await _db_get_devices();
    DEVICES = new DeviceCollection(__devices);
    console.log(a()) <-- **Returns the object correctly**
  } finally {
    console.log("Login Initialised!");
  }
}

module.exports = { init, a }

Below is the code that is having issues:以下是有问题的代码:

App.js应用程序.js

const Login = require('./func/Login');

Login.init() <-- **runs init function no issues**

console.log(Login.a()); <-- **returns undefined**

I have figured that its something to do with async but that is why i setup a function to call it later so not sure if there is a better method to calling the variable when its set.我认为它与异步有关,但这就是为什么我设置一个 function 以便稍后调用它,所以不确定是否有更好的方法在设置变量时调用它。

init is an async function, so following statement init是一个异步 function,所以下面的语句

console.log(Login.a())

will run before init function has executed completely.将在init function 完全执行之前运行。 Hence you get undefined because DEVICES isn't initialized yet.因此,您会得到未定义,因为DEVICES尚未初始化。

You can return DEVICES from the init function and call init function as shown below您可以从init function 返回DEVICES并调用init function ,如下所示

Login.init()
  .then(data => console.log(data))    // log the return value of init function
  .catch(error => console.log(error);

or you could call function a after init function has executed completely或者您可以在init function 完全a后调用 function

Login.init()
  .then(() => console.log(Login.a()))
  .catch(error => console.log(error);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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