Vikas Kumar Vikas Kumar - 26 days ago 18
Javascript Question

How to return value from this function?

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;
}

Answer

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
});
Comments