Thomas Bridges
Thomas Bridges

Reputation: 11

Node.js mysql saving results of query into a variable for later use

EDIT: Solution after my initial question at the bottom!

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)

SOLUTION: The whole point of this was to query my database which holds info on the members of my discord server. The final console log is undefined but once the bot loads up 'members' has the results of my query in an object array like I wanted.

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() {
        members = await new Promise((resolve) => {
            connection.query('Select * from MEMBER', (err, res) => {
                resolve(res)
            })
        }).then(res => {
            return res
        });
}
members = getMembers()
console.log(members)

Upvotes: 1

Views: 746

Answers (2)

Tuan Pham
Tuan Pham

Reputation: 56

getMembers() is an async function so that it will return an promise, you may want an await before it

Upvotes: 0

Liam Welsh
Liam Welsh

Reputation: 314

Try members = await getMembers()

Upvotes: 1

Related Questions