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?

4

1 回答 1

2

connection.query是异步的,因此您必须使用回调函数来处理查询结果。

这是您的代码稍作修改:

API路线:

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

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

获取数据函数:

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();
}
于 2013-09-12T12:28:45.027 回答