0

I have a function that gets users emails given an array of roles ids and a given course id. I am trying to return that array containing all the users but the return is happening before SQL select. So it appear the array never gets populated.

Below is my function:

function getUsersWithRoles(roles, course_id) {
     let arr = [];
     roles = roles.split(',');

     // MySQL connection func
     connect((con) => {
          let query = `select * from roles join users on users.id = roles.users_id where roles.id in(${roles.join(',')}) and roles.course_id = ?`;
          let values = [course_id];
          try {
               con.query(query, values, (error, result, fields) => {
                    if (error) {
                         throw err;
                    }else {
                         result.foreach((user) => {
                              arr.push(user);
                              // I am only able to access the pushed users here ...
                         });
                    }                    
               })
          }catch(err) {
               console.log(err)
          }          
     });

     // This runs before my connection so it returns empty array :(
     return arr;
}

If it helps, below is the function I use that makes my SQL connection

module.exports = (cb) => {
    try {
        // try to establish connection w/ info from .env
        var con = mysql.createConnection({
            host: process.env.DB_HOST,
            user: process.env.DB_USERNAME,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_DATABASE
        });
    }catch (err) {
        console.log(`ERROR: connect: mysql.createConnection(): ${err}`);
    }
    con.connect((err) => {
        if (err) {
            console.log(`ERROR: connect: con.connect(): ${err}`);            
        }else {
            try {
                cb(con);
            }catch (err) {
                console.log(`ERROR: connect: cb(con): ${err}`);                
            }
            setTimeout(() => {
                // Close the connection after an allotted time
                try {
                    con.end();                    
                }catch (err) {
                    console.log(`ERROR: connect: con.end(): ${err}`);                    
                }
            }, 60 * 1000);
        }
    });
}

Thanks in advance!!

Tanner
  • 720
  • 1
  • 8
  • 17
  • If your function relies on asynchronous work to get its result (async/await, promises, callbacks) it needs to also be asynchronous itself (return a promise, invoke a callback instead of returning, use async/await). – CollinD Nov 20 '19 at 19:10
  • @CollinD So where I try to push my users into the array, is that where the callback (or 1 of the others mentioned) needs to go? – Tanner Nov 20 '19 at 19:16
  • return arr in your else block after the result.foreach. – shobeurself Nov 20 '19 at 19:34
  • @shobeurself When I added the return after the foreach it returned undefined. Also, I sort of simplified my question so I could get part of it working, I pass more parameters into this function so I don't necessarily want to escape right away. Thanks for helping tho! :) – Tanner Nov 20 '19 at 20:06

0 Answers0