Returning SQL query results as a variable in node.js

Problem

I'm trying to grab the results of an SQL query in order to use it elsewhere in my code, but I just can't figure out how to get them out. I have nested functions so I tried to get it out through two calls of return, but what comes out isn't valid.

var users = getUsers();


function getUsers(req, res){
  dbConnect(req,res);
  return connection.query('SELECT * FROM USERS', function selectAll(err, rows, fields) {
    if (err) {
        throw err;
    }
    for (var i in rows) {
        console.log(rows[i]);
    }
    return rows;
    dbClose(req,res);
  })
}

What's wrong here?

Problem courtesy of: karoma

Solution

connection.query is an asynchronous function.

rows is only available within the selectAll function. If you'd like to do something with the rows, you need to do it from selectAll.

users will be undefined because the function getUsers itself does not return anything (and can not return rows.

Instead of doing

users = get Users();
doSomethingWithUsers(users);

do this instead:

getUsers();

function getUsers(req, res){
  dbConnect(req,res);
  return connection.query('SELECT * FROM USERS', function selectAll(err, rows, fields) {
    if (err) {
        throw err;
    }
    for (var i in rows) {
        console.log(rows[i]);
    }
    doSomethingWithUsers(rows);
    dbClose(req,res);
  })
}

Or pass a callback function in getUsers that gets passed the result.

Solution courtesy of: Pascal Belloncle

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.