简体   繁体   中英

Returning SQL query results as a variable in node.js

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?

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.

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