user3821280
user3821280

Reputation: 39

How to properly export/require

I'm trying to export one function this way:

exports.query = function(request){
    conn.query(request, function(err, rows, fields){
        if(err) console.log(err);
        return rows[0].id;
    });
}

and using it:

var mysql = require('./mysql');
console.log(mysql.query('SELECT * FROM tablename'));

Proceeding this way for getting a result involves undefined as output. How do I to fix this, please?

Note that when I just type console.log(rows[0].id) instead of return rows[0].id it sends back 123.

Thanks in advance!

Upvotes: 0

Views: 29

Answers (2)

tehsis
tehsis

Reputation: 1612

That's a problem of synchrony.

the conn.query function returns undefined because it finish its execution before the results are fetched (like almost any i/o related operation on js/node).

One possible solution to that, is to provide a callback to your query function.

exports.query = function(request, cb){
  conn.query(request, function(err, rows, fields){
    // some "special" processing
    cb(err, rows, fields);
  });
};

If you're not familiar with async functions, take a look on some articles about that:

http://justinklemm.com/node-js-async-tutorial/ https://www.promisejs.org/

Upvotes: 0

Kevin Reilly
Kevin Reilly

Reputation: 6252

In your example, the output is being returned to the anonymous function of the database query instead of the caller of the module. You can use a callback to return output to the caller of the module.

exports.query = function(request, callback){
    conn.query(request, function(err, rows, fields){
        if (err) {
            callback(err);
        } else {
            callback(null, rows[0].id);
        }
    });
}

Then call it like

var mysql = require('./mysql');
mysql.query('SELECT * FROM tablename', function(err, results){
    if (err) {
        console.error(err);
    } else {
        console.log(results);
    }
});

Upvotes: 2

Related Questions