1

trying to gather some titles from my roles table and put them into an array so i can loop over them later but when i run the function it doesn't give me a array with the values I'm guessing

function setRoles() {
    let roleSet = [];

    let sql = "SELECT * FROM role";
    connection.query(sql, function(err, res) {
        if (err) throw err;
        for (let i = 0; i < res.length; i++) {
            roleSet.push(res[i]);

        }



    });
    console.log(roleSet);
    return roleSet;

}

here is the code the only thing i get back is a empty array and ive tried putting the array init outside the function and that doesnt work either

JimClayton
  • 111
  • 1
  • 4
  • 15

1 Answers1

1

How about change console.log after query?
It maybe not return anything.

You can change setRoles function as async, but I can't make async/await code perfectly.

So, I reference another module(async) for use mysql.

function setRoles() {
    let roleSet = [];

    let sql = "SELECT * FROM role";
    connection.query(sql, function(err, res) {
        if (err) throw err;
        for (let i = 0; i < res.length; i++) {
            roleSet.push(res[i]);
        }
        console.log(roleSet);
        //return roleSet;
    });
    //console.log(roleSet);
    //return roleSet;
}
connection.query('SELECT * FROM some_table', (err, rows) => {
    // do something with the results here
});
// the following code is executed *before* the query is executed

I reference stackoverflow answer code.

Zem
  • 464
  • 3
  • 14