简体   繁体   中英

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

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)

Try members = await getMembers()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM