CodeFoodPixels / node-promise-mysql

A wrapper for mysqljs/mysql that wraps function calls with Bluebird promises.
MIT License
338 stars 64 forks source link

Get result rows on then not working #85

Closed MatiasManevi closed 6 years ago

MatiasManevi commented 6 years ago

Hi everyone. Im trying to chain a few sql's.

I have some relationships and i want them to be correctly expressed on my final json. But for some reason i can not get the row result from de promise. For example in this piece of code:

var mysql = require('promise-mysql');

mysql.createConnection({
    host: 'localhost',
    user: 'sauron',
    password: 'theonetruering',
    database: 'mordor'
}).then(function(conn){
    var result = conn.query('select `name` from hobbits');
    conn.end();
    return result;
}).then(function(rows){
    // Logs out a list of hobbits
    console.log(rows);
});

console.log(rows) always prints "undefined". What am I doing wrong.

This is my code:

mysql.createConnection({
        host: "localhost",
        user: "xxxi",
        password: "xxxx",
        database: "xxxx"
    }).then(function(conn){
        connection = conn;`
               return connection.query('SELECT * FROM tickets WHERE sale_details_id='+sale_details[1].id).then(function(result){
                sale_details[1]['tickets'] = [];
                sale_details[1]['tickets'].push(result[0]);
            });
        }).then(function(rows){
            console.log(rows) // this is undefined

        return connection.query('SELECT * FROM passengers WHERE id=' + rows[0].passenger_id).then(function(result){
            passengers = result;
                    console.log(passengers)
        });
CodeFoodPixels commented 6 years ago

Where you're doing this:

return connection.query('SELECT * FROM tickets WHERE sale_details_id='+sale_details[1].id).then(function(result){
                sale_details[1]['tickets'] = [];
                sale_details[1]['tickets'].push(result[0]);
            });

Anything returned from the .then is passed on to the chain where you're doing the console log. You're not returning anything so rows will be undefined.