Thursday 8 June 2017

Return value from inner function of a function node.js / MySQL

I'm working on a very simple web app that doesn't do much, however it does connect to a database for INSERT and SELECT operations on one table. I have a function that I utilized while browsing through several great tutorials, however I'm having trouble returning the rows from the SELECT query. Keeping in mind I'm learning Node.JS -- how would I display the data returned from the query (SELECT) to this block?

app.post("/getcsv", function(req,res){

var sqlselall = "SELECT * FROM office";
var rows = handle_database(sqlselall);
res.json(rows);
res.end();

The function for handling the database connections (using pooling):

function handle_database(sqlstmt){

pool.getConnection(function(err,connection){

    if(err) {
        res.json({"code" : 100, "status" : "Error in connection to database."});
        return;
    }

    console.log('connected as id ' + connection.threadId);

    connection.query(sqlstmt, function(err,rows){
        connection.release();
        if(!err){
            console.log("Number of rows affected: " + rows.affectedRows);
        }

    });

    connection.on('error', function(err) {
        res.json({"code": 100, "status" : "Error in connection to database."});
        return;
    });

I realize that the rows in the inner function contains the data I need, however I'm at a loss as to how to return it when I call the function.



via SmittyWerbenJägerManJensen

No comments:

Post a Comment