1

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)

2 Answers 2

1

Try members = await getMembers()

Sign up to request clarification or add additional context in comments.

3 Comments

I tried that and I get the error "await is only valid in async functions and the top level bodies of modules"
If you are interested I found a solution
Ah put it in an async function then.
0

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

5 Comments

I did try that as well but I got the error "await is only valid in async functions and the top level bodies of modules"
oh, my bad. How about you use .then(...).catch(...) after getMembers() function?
If you are interested I found a solution
sure. can you tell me the solution?
I added it in question area above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.