1

I'm learning Node.js and I'm just starting to work with some MySQL connections. I have a function which is supposed to get a set of rows from the database. However I can't get the value from it.

//connect.js
var mysql = require('mysql');
module.exports = {
    world : function () {
        var conn = mysql.createConnection({
            host : '',
            user : 'root',
            password : '',
            database : ''
        });
        conn.connect(function(err){
            if(err) throw err;
        });
        conn.query('SELECT * FROM `room` WHERE 1', function(err, result, fields){
            if(err) throw err;
            var id = JSON.stringify(result[0].id);
            var name = JSON.stringify(result[0].name);
            var time = JSON.stringify(result[0].time);
            return time;
        });
        conn.end(function(err){
            if(err) throw err;
        })
      }
};

And I try to get the value by this program:

//show.js
var hello = require('./connect');
console.log(hello.world());

The result like this:

$ node show
undefined

So how should I get the value?

1 Answer 1

1

You cannot just return an asynchronous value inside your connect.js. To return this value time, you have to pass by a callback function, or a promise.

This is an example of a callback :

//connect.js
var mysql = require('mysql');
module.exports = {
    world : function (callback) { // Now world method takes a callback function parameter
        var conn = mysql.createConnection({
            host : '',
            user : 'root',
            password : '',
            database : ''
        });
        conn.connect(function(err){
            if(err) callback(err, null);  // Callback an error
        });
        conn.query('SELECT * FROM `room` WHERE 1', function(err, result, fields){
            if(err) callback(err, null);  // Callback an error
            else {
                var id = JSON.stringify(result[0].id);
                var name = JSON.stringify(result[0].name);
                var time = JSON.stringify(result[0].time);
                callback(null, time); // callback your response here
            }
        });
        conn.end(function(err){
            if(err) callback(err, null); // Callback an error
        })
    }
};

And this is how you can get the response

//show.js
var hello = require('./connect');
hello.world(function(err, response) {
    if (err) throw err;
    console.log(response);
});

I suggest you to learn more about Javascript asynchronous

Hope it helps.

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.