I need some help to understand the reason of why after a forEach my const is getting empty. I read and find some questions but none of them help me understand. I believe that is happening because JS is asynchronous, but I can't figure out how to solve myself.
So, the code is very simple I have a NodeJS API that will connect to more then one database, and return all the info. I am using pg-promise to connect to PostgreSQL.
export default class AllInfo {
constructor(databases) {
this.databases = databases;
this.options = {
promiseLib: promise,
};
this.databaseConnection = new Pg(this.options);
}
And after that, the trick method:
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;
}
In this code, my return is always empty ([]) when it is requested.
If I log the const entidades inside the loop, the information is logged successfully. But if I log after the loop and before the return, it is empty.
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;
}
And if I try to log outside:
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;
}
Someone can explain why this happens and where I look for the solution?