0

I am new to node.js , and use ari client. I have two .js files that first one is required in second one. I have declared a variable in second one that must contain return value of first file but console.log(variable) is undefined although in first file return value is not null.

in first file :

var db = require("./database.js");
var service_info = db.select(connection,'select * from services where ivr_shortcode = ?',service);
console.log(service_info);

service_info is undefined;

in second file :

this.select = function (connection,query,data){
connection.query(query,[data],function(err, results){
    if(err)
    {
        throw err;
    }
    else
    {
        return results;
    }
});}
Hedi
  • 322
  • 4
  • 17
  • Duplicate of http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – Scimonster Nov 16 '14 at 13:02

3 Answers3

2

You cannot just return values from callback due to call being asynchronous, you should use another function to get the results:

// file 'database.js'
exports.select = function (connection, query, data, callback) {
    connection.query(query, [data], callback);
}

Than in your main:

// I assume `connection` and `service` are defined somewhere before (like in your original code)
var db = require("./database.js");
var service_info = db.select(connection,'select * from services where ivr_shortcode = ?',service, function(err, service_info){
  console.log(service_info);
});

P.S. You should really read some docs and look into Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference to get better understanding of scope visibility and closures

Community
  • 1
  • 1
Juicy Scripter
  • 25,778
  • 6
  • 72
  • 93
0

To deal with such condition you needs to implement it using the async/await.

exports.select = async function (connection,query,data){
await connection.query(query,[data],function(err, results){
    if(err){
        throw err;
    }else{
        return 
    }
  });
}

This will waits until you get the result. So undefined condition never arise.

-1

you have to export select. something like this :

exports.select = function (connection,query,data){
connection.query(query,[data],function(err, results){
    if(err)
    {
        throw err;
    }
    else
    {
        return 
    }
});}
Mohammad Rahchamani
  • 5,002
  • 1
  • 26
  • 36