0

This is code in my node.js project but I can't access the value of connection2. I read somewhere that .getConnection is asynchronous function so I can't get the value of connection2 this way. How can I modify this code to properly return the value?

var mysql = require('mysql');
    var connectionPool = mysql.createPool({
        host: 'localhost',
        user: 'root',
        password: '',
        database: 'rockcity_followme'
    });
exports.connExport=function() {
    var connection2;
    connectionPool.getConnection(function (err, connection) {
        connection2=connection;
    });
    return connection2;
}
user3.14
  • 371
  • 2
  • 15

1 Answers1

0

You cannot return the connection here. It must be asynchronous, so you take a callback as a parameter and call the callback when you have the connection.

exports.connExport=function(callback) {
    connectionPool.getConnection(function (err, connection) {
        callback(connection);
    });
}

See this for more information about asynchronous vs synchronous functions in node.


When a function does anything asynchronously, it has to be asynchronous all the way up. To use connExport from another module, it must be used asynchronously.

var yourModule = require("yourModule");
yourModule.connExport(function(connection) { // <-- the callback function
    // you can use connection here
});
Community
  • 1
  • 1
afuous
  • 1,478
  • 10
  • 12