0

I have a common module that will be used by several apps. The module has a object that has several methods. I import the object through the require statement but I am having problem in understanding how I can get the returned value in an asynchronous programming model. Let me clarify it here in the following over-simplified pseudo-code:

File common_module.js:

var mysql = require('mysql');
exports.f1 = function() {
 var connection_pool = mysql.createPool({host: 'xxx', user:..});
 connection_pool.getConnection(function(err, connection) {
    connection.query('SELECT c1 from t1 where c2 =  ?', value, function(err, rows)  {
                     value_to_return  = rows[0].content; //string type
    });
 });
 return (value_to_return);
}

The main app is, lets say, main.js:

db_getval = require('./common_module.js');
console.log(db_getval.f1());

It will always complain that value_to_return is undefined because the return statement is executed without waiting for the query to complete (thanks to asynchronous programming model). Though this is a mysql query related problem here, it will be true for many other scenarios too. How do I get around this? I am missing something basic here...

Sunny
  • 9,245
  • 10
  • 49
  • 79
  • 1
    This has nothing to do with the fact that this is a module and everything to do with the fact that it is impossible to do what you are trying to do. You should instead be returning a promise, or accepting a callback as a parameter. You **cannot** return the value. – Kevin B Sep 21 '15 at 17:55
  • @Kevin B Yes, it has nothing to do with module. I realize it now. As you can tell, I am not very comfortable yet with this async way of programming. Promises are not fully supported. "Accepting a callback" in the above scenario - can you elaborate a bit. – Sunny Sep 21 '15 at 18:01
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Aaron Dufour Sep 21 '15 at 18:16

1 Answers1

1

In this case, you can either use promises, or callbacks.

Callbacks in node are sort of the de-facto way of handling this kind of work:

var mysql = require('mysql');
exports.f1 = function (cb) {
    var connection_pool = mysql.createPool({
        host: 'xxx',
        user: ..
    });
    connection_pool.getConnection(function (err, connection) {
        if (err) {
            return cb(err);
        }
        connection.query('SELECT c1 from t1 where c2 =  ?', value, function (err, rows) {
            if (err) {
                return cb(err);
            }
            cb(null, rows[0].content);
        });
    });
};

// usage...
theModule(function (err, result) {
    console.log(err, result);
});

That said, with the introduction of promises in node 0.12, promises are becoming far more popular due to more robust error handling. (Chaining is also very useful)

var mysql = require('mysql');
exports.f1 = function (cb) {
    return new Promise(function (resolve) {
        var connection_pool = mysql.createPool({
            host: 'xxx',
            user: ..
        });
        connection_pool.getConnection(function (err, connection) {
            if (err) {
                throw err;
            }
            connection.query('SELECT c1 from t1 where c2 =  ?', value, function (err, rows) {
                if (err) {
                    throw err;
                }
                resolve(rows[0].content);
            });
        });
    });
};

// usage...

theModule().then(function (result) {
    console.log(result);
}).catch(function (err) {
    console.log(err, err.stack);
});
Kevin B
  • 94,570
  • 16
  • 163
  • 180