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

问题描述 投票:0回答:1

嘿,我陷入无法访问我已在nodejs模块中设置的变量的情况,该变量已与模块导出一起公开以从主文件访问,下面将向您显示:

Login.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 }

下面是有问题的代码:

App.js

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

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

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

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

javascript node.js
1个回答
0
投票

[init是一个异步函数,因此下面的语句

console.log(Login.a())

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

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

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

或者您可以在a函数完全执行后调用函数init

Login.init()
  .then(() => console.log(Login.a()))
  .catch(error => console.log(error);
© www.soinside.com 2019 - 2024. All rights reserved.