I want to save the results of my query from mysql into a variable. I know I can do stuff as long as I am in the callback or .then(). The problem I'm having is I want to load all of the member_ids (which get returned from the query) one time and use them when I want later. These values do not change and I don't want to keep querying the database everytime I want to access a member's ID. When going top to bottom, the first console.log has my results but the second one is undefined.
let members;
let connection = mysql2.createConnection({
host: config.mysqlConnection.hostName,
user: config.mysqlConnection.userName,
password: config.mysqlConnection.password,
database: config.mysqlConnection.databaseName
});
connection.connect();
async function getMembers() {
const result = await new Promise((resolve) => {
connection.query('Select * from MEMBER', (err, res) => {
resolve(res)
})
})
console.log(result);
return result;
}
members = getMembers()
console.log(members)
CodePudding user response:
Try members = await getMembers()
CodePudding user response:
getMembers()
is an async function so that it will return an promise, you may want an await
before it