0

I'm using node mysql to connect to an external DB and I can console.log the query results but when I try to return the data I get Promise pending.

Here is the function -

export function get_info() {

    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'xxxxxx',
        user: 'bob',
        port: 'xxxx',
        password: 'bob',
        database: 'li_webform'
    });

    connection.connect(function (err) {
        if (err) throw err;
        connection.query("SELECT Name FROM webform", function (err, result) {
            if (err) throw err;
            //console.log(result); **This works**
            //console.log(result[0].Name);
            return result;
        });
    });
}

I'm trying to set a variable equal to the return value like this

var newVar = get_info();
console.log(newVar);

but I got the promise pending note. I believe this has something to do with the Asynchronous nature of JavaScript. I've tried following this post How to properly return a result from mysql with Node? but can't get it working.

Here is what I tried following that post

export function get_info(callback) {

    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'xxxxx',
        user: 'bob',
        port: 'xxxxxx',
        password: 'bob',
        database: 'li_webform'
    });

    connection.connect(function (err) {
        if (err) throw err;
        connection.query("SELECT Name FROM webform", function (err, result) {
            if (err) throw err;
            //console.log(result);
            //console.log(result[0].Name);
            return callback(result);
        });
    });
}

Then I try to use it via

var stuff_i_want = '';

get_info(function (result) {
    stuff_i_want = result;
    console.log(stuff_i_want);
});

But I get no output

Edit** Here is new attempt

export function get_info() {

    var mysql = require('mysql');
    var connection = mysql.createConnection({
        host: 'xxxx',
        user: 'bob',
        port: 'xxxxxx',
        password: 'bob',
        database: 'li_webform'
    });

    connection.connect(function (err) {
        if (err) throw err;
        connection.query("SELECT Name FROM webform", function (err, result) {
            if (err) throw err;
            //console.log(result);
            //console.log(result[0].Name);
            return result;
        });
    });
}

and second part

    get_info().then((callbackData)=>{
   console.log("Data: ", callbackData)
 }).catch((error)=>{
    console.log("Error", error)
 });
franchyze923
  • 1,060
  • 2
  • 12
  • 38

1 Answers1

0

The function returns a promise. You can handle it like this:

 get_info().then((callbackData)=>{
   console.log("Data: ", callbackData)
 }).catch((error)=>{
    console.log("Error", error)
 });