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



嘿,我陷入了无法访问我在 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**

我认为这与异步有关,但这就是为什么我设置了一个函数稍后调用它,所以不确定是否有更好的方法来调用变量。

init

是一个异步函数,所以以下语句

console.log(Login.a())

将在函数完全执行之前运行init。因此,您未定义DEVICES因为尚未初始化。

您可以从init函数返回DEVICES并调用init函数,如下所示

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

或者你可以在函数完全执行后调用函数ainit

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

最新更新