1

I'm trying to use connection from a connection.js file and use it in different file webFrontend.js using exports object. Now what I get on running server is:

{
  "Result": "undefinedThis is result"
}

That means connection is not defined. Why is it happening? connection is working fine if getConnection is created in same (webFrontend.js) file, but the problem is when I use getConnection in same exports function in connection.js hence the connection not defined error:

Here are 2 necessary files (routes file has no problem) that explains what I'm doing:

connection.js

var mysql = require('mysql');
exports.connExport = function () {
    var connectionPool = mysql.createPool({
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'rockcity_followme'
    });
    if(connectionPool) {
        connectionPool.getConnection(function (err, connection) {
            if (err) {
                return err;
            } else {
                return connection;
            }
        });
    }else{
        var abc="return error";
        return abc;
    }
}

webFrontend.js

var connObj=require('../Routes/connection.js');
var connection=connObj.connExport();
exports.getIndivRecords= function(req, res, next){
res.send({
    Result: connection+"This is result"
});
    return next();
};
user3.14
  • 371
  • 2
  • 15
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JJJ Nov 09 '16 at 07:29
  • I don't understand what it has about my question? – user3.14 Nov 09 '16 at 07:36
  • `connectionPool.getConnection` is an asynchronous function. Why do you think it has a callback parameter? – JJJ Nov 09 '16 at 07:37
  • So is there any way to solve? Would I need it export separately below the connectionPool export? – user3.14 Nov 09 '16 at 07:44
  • Yes, there is a way to solve it. Read the duplicate. – JJJ Nov 09 '16 at 07:45

2 Answers2

0

No need for the .js file extension, it's automagically added for you.

The code below uses standard error-first callbacks

webFrontend.js

var connection = require('../Routes/connection');
exports.getIndivRecords = function(req, res, next){

  // connection takes a standard error-first callback
  connection(function(err, conn){
    if (err) {
      // Handle the error returned
      console.log(err);
    }
    // The database connection is available here as conn
    console.log( "Connection:" + conn);

    // presumably you want to do something here
    // before sending the response

    res.send({
      Result: conn + "This is result"
    });
  });
  return next();
};

connection.js

var mySQL = require('mysql');
var connectionPool = mySQL.createPool({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'rockcity_followme'
});
var getConnection = function (cb) {
  connectionPool.getConnection(function (err, connection) {
    // pass the error to the callback
    if (err) {
      return cb(err);
    }
    cb(null, connection);
  });
};
module.exports = getConnection;
Dan Nagle
  • 4,384
  • 1
  • 16
  • 28
0

First of all @Dan Nagle was right no need of .js

Second You are getting the connection undefinded because still the method doesnt returned with result.

Use promise to call your Connection.js method

Your node is single threaded async execution, He doest wait for the method to return a result

1) Problem with your javascript is that

var connection=connObj.connExport();

in Creation stage connection was defined by javascript as undefined and as connObj.connExport(); as still not returned with answer it executed this function in which connection was undefined

exports.getIndivRecords= function(req, res, next){
res.send({
    Result: connection+"This is result"
});

Use promise read this first so you can understand something about promise and callback if you are unable to solve than comment i will play with it.But first you try.Thanku

Understanding promises in node.js

Ok Try This I have used promise here

var connObj = require('../Routes/connection');
connObj.connExport().then(
    function (connection) {
        exports.getIndivRecords = function (req, res, next) {
            res.send({
                Result: connection + "This is result"
            });
            return next();
        };
    }).catch(function (err) {
    res.status(400).send(err);
    return;
});




var mysql = require('mysql');
exports.connExport = function () {
    return new Promise(function (fulfill, reject) {
    var connectionPool = mysql.createPool({
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'rockcity_followme'
    });
    if (connectionPool) {
        connectionPool.getConnection(function (err, connection) {
            if (err) {
                return reject(err);
            } else {
                return fulfill(connection);
            }
        });
    } else {
        var abc = "return error";
        return reject(abc);
        }
    });
}
Community
  • 1
  • 1
Parshuram Kalvikatte
  • 1,616
  • 4
  • 20
  • 40