Vikas Kumar Vikas Kumar - 1 year ago 100
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

. 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) {
return connection2;

Answer Source

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) {

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download