2

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

3
  • Simply, replace console.log and return statement in connection.query. You can make connection.query as async function and get with await. Commented Apr 5, 2021 at 2:12
  • i change it and i get a promise pending ? Commented Apr 5, 2021 at 2:17
  • Yes. In my case, I use async module. Commented Apr 5, 2021 at 2:21

1 Answer 1

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.

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

Comments

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.