0

I am still a beginner in JS here i am trying to pass the value of x to y tried y=x but didnt work y is returned as undefined and x is returned as an array of values

exports.Get_info = function (name) {
   var y;
   db.query(query, params, function (err, results) {
      if (err) {  
         console.log('Error');
         throw err;
      } 
      var x = results.map(function (result) {
         data1 = result['name'];
         return data1;
      });
      console.log("x = " + x);
      y = x;
      return x;
   });
   console.log("y = " + y)
   return y;
}
Artyom Neustroev
  • 8,224
  • 4
  • 29
  • 54
daredevil
  • 107
  • 1
  • 7

1 Answers1

1

What happens is that return y is executed before the db.query finishes. That's why the y is undefined when it returns. You should rewrite your code to be asynchronous using a callback.

exports.getInfo = function (name, callback) {

    db.query(query, params, function (err, results) {

        if (err){
            console.log('Error',err);
            return callback(err);
        }

        var x = results.map(function (result) {
            data1 = result['name'];
        });

        return callback(null, x);
    });
};

On a side note you should use camelCase for variable and function naming.

Osukaa
  • 688
  • 2
  • 10
  • 22