1

var data;
function initM(){
    var mysql = require('mysql'); 
    
    var con = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "",
        database:"ns2"
      });

      sql="SELECT id,first_name,last_name from stu_details";
      con.connect(function(err) {
      
        if (err) throw err;
        console.log("Connected!");
       con.query(sql,function (err, result) 
        {if (err) throw err;
        data=result;//----> I want to save the returned result from the query in "data"
        console.log(result);//--> prints the data of query
        });
        });
}


console.log(initM());
console.log(data);//--> prints "undefined"

I want to save the returned result from the query in a variable and use it in another function. prints "undefined" tanks!

  • console everywhere to find where is error! – Ericgit Nov 24 '19 at 19:31
  • here you can find some helpful resource https://www.w3schools.com/nodejs/nodejs_mysql_select.asp – Ericgit Nov 24 '19 at 19:34
  • Console variable data after saving result in it inside initM function to check whether result is being saved in variable data or not. –  Nov 24 '19 at 19:34

1 Answers1

0

You are working with async functions (like con.query). That means that your data will be stored when the query ended. Your code continues meanwhile.

You can use promises and async functions to solve this problem.

var data;
async function initM() {
    return new Promise((resolve) => {
        var mysql = require('mysql');

        var con = mysql.createConnection({
            host: "localhost",
            user: "root",
            password: "",
            database: "ns2"
        });

        sql = "SELECT id,first_name,last_name from stu_details";
        con.connect(function (err) {

            if (err) throw err;
            console.log("Connected!");
            con.query(sql, function (err, result) {
                if (err) throw err;
                data = result;//----> I want to save the returned result from the query in "data"
                console.log(result);//--> prints the data of query
                // now the variable is set
                resolve();
            });
        });
    });
}

async function start() {
    await initM();
    console.log(data);//--> should print your data
}
start();
Matthias Gwiozda
  • 505
  • 5
  • 14