使用forEach通过push方法创建另一个数组,但是在循环结束之后,该数组为空

时间:2018-09-13 15:48:39

标签: javascript node.js ecmascript-6

我需要一些帮助来理解为什么forEach之后我的const变空的原因。我阅读并发现了一些问题,但是没有一个问题能帮助我理解。我相信这是因为JS是异步的,但我不知道该如何解决。

因此,代码非常简单,我有一个NodeJS API,它将连接到多个数据库,并返回所有信息。我正在使用pg-promise连接到PostgreSQL。

export default class AllInfo {
  constructor(databases) {
    this.databases = databases;
    this.options = {
      promiseLib: promise,
    };
    this.databaseConnection = new Pg(this.options);
  }

然后是把戏方法:

 getAllInformation() {
    const entidades = [];
    this.databases.getStringConnection().forEach((db) => {
      const connection = this.databaseConnection(db);
      connection.any('SELECT * FROM information').then((data) => {
        entidades.push(data);
      });
      connection.$pool.end();
    });
    return entidades;
  } 

在此代码中,我的返回要求始终为空([])。

如果我在循环内记录了常数,信息将被成功记录。但是,如果我在循环之后和返回之前登录,则为空。

 getAllInformation() {
    const entidades = [];
    this.databases.getStringConnection().forEach((db) => {
      const connection = this.databaseConnection(db);
      connection.any('SELECT * FROM information').then((data) => {
        entidades.push(data);
        console.log(entidades) // here it works
      });
      connection.$pool.end();
    });
    return entidades;
  } 

如果我尝试登录外部:

 getAllInformation() {
    const entidades = [];
    this.databases.getStringConnection().forEach((db) => {
      const connection = this.databaseConnection(db);
      connection.any('SELECT * FROM information').then((data) => {
        entidades.push(data);

      });
      connection.$pool.end();
    });
    console.log(entidades) // here doesn't work
    return entidades;
  }

有人可以解释为什么会发生这种情况以及我在哪里寻找解决方案?

1 个答案:

答案 0 :(得分:0)

connection.any()返回一个诺言并执行匿名函数,该函数将在解决诺言后将数据推送到您的数组中。这就是为什么匿名函数异步执行的原因。但是,您可以等待像这样的任何函数返回数据:

let data = await connection.any('SELECT * FROM information');
entidades.push(data);