0

I am developing a small program using Node.js, Express and EJS.

Basically i have a post api route as follows:

app.post('/getJson', function (req, res) {

    var jsonData = fetchData(req.body.selectpicker);
    console.log('jsonData' + jsonData);
    res.render('result.ejs', {
            html: '<p>' + jsonData + '</p>'
    });
});

The fetchdata function does the following:

function fetchData(tableName)
{
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
        host : 'xxxx',
        user : 'xxxx',
        password : 'xxxx!',
        database : 'xxxxx',
        port : 'xxxx'

    });

    connection.connect(function(err) {
        console.log('error' + err);
        // connected! (unless `err` is set)
    });

    var query = "SELECT * FROM " + tableName;
    var data = [];
    connection.query(query, function(err, rows, fields)
    {
        if (err) throw err;
        data = rows;

        console.log('The rows are: ', rows);    
    });

    connection.end();
    console.log('datsa' + data);
    return data;
}

But my issue is that when the connection.query first runs it doesn't go into it the callback function instead it goes straight to connection.end(). But then after it goes out of the fetchData function it then goes and runs the callback function which returns the rows after the query?

Any ideas?

I think it might be to do with the way the api's work?

1
  • node js is an event driven programming so it follows the sequence of events Commented Sep 12, 2013 at 12:24

1 Answer 1

2

connection.query is asynchronous, so you'll have to use a callback function to handle the result of the query.

Here's your code slightly modified:

API route:

app.post('/getJson', function (req, res) {

    fetchData(req.body.selectpicker, function(jsonata) {
        console.log('jsonData' + jsonData);
        res.render('result.ejs', {
            html: '<p>' + jsonData + '</p>'
        });
    });
});

The fetchdata function:

function fetchData(tableName, done)
{
    var mysql      = require('mysql');
    var connection = mysql.createConnection({
        host : 'xxxx',
        user : 'xxxx',
        password : 'xxxx!',
        database : 'xxxxx',
        port : 'xxxx'

    });

    connection.connect(function(err) {
        console.log('error' + err);
        // connected! (unless `err` is set)
    });

    var query = "SELECT * FROM " + tableName;

    connection.query(query, function(err, rows, fields)
    {
        if (err) throw err;
        console.log('The rows are: ', rows);   
        done(rows); 
    });

    connection.end();
}
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.