简体   繁体   中英

node.js flow not correct when getting data from mysql database

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?

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

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