[英]Unable to access Variable value using nodejs exports?
嘿,我陷入了一种情况,我无法访问我在 nodejs 模块中设置的变量,我已经通过模块导出公开了从主文件访问的变量,我将在下面向您展示:
登录.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 }
以下是有问题的代码:
应用程序.js
const Login = require('./func/Login');
Login.init() <-- **runs init function no issues**
console.log(Login.a()); <-- **returns undefined**
我认为它与异步有关,但这就是为什么我设置一个 function 以便稍后调用它,所以不确定是否有更好的方法在设置变量时调用它。
init
是一个异步 function,所以下面的语句
console.log(Login.a())
将在init
function 完全执行之前运行。 因此,您会得到未定义,因为DEVICES
尚未初始化。
您可以从init
function 返回DEVICES
并调用init
function ,如下所示
Login.init()
.then(data => console.log(data)) // log the return value of init function
.catch(error => console.log(error);
或者您可以在init
function 完全a
后调用 function
Login.init()
.then(() => console.log(Login.a()))
.catch(error => console.log(error);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.