Ted sie
Ted sie

Reputation: 13

How to get the return value from Node.js function which contains DB query from another application

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?

Upvotes: 1

Views: 86

Answers (1)

Sparw
Sparw

Reputation: 2743

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.

Upvotes: 1

Related Questions