0

hi everyone i cannot able to figure what is happening can anyone help me out i am new to electron , i need to take values from database (MySQL) where when i hit console.log(rows) i received the object values but when i return the rows to other function it shows undefined can any one help me to fix this.

 @ 
       <html>
   <head>
      <meta charset="UTF-8">
     <title>Hello World!</title>
   </head>
    <body>
  <h1>Connecting to MySQL</h1>
  <br>
  <input type="button" id="action-btn" onclick="a1()" value="Retrieve 10 
     first rows in the database" />
  <table id="table" border="1">
     <tbody>
     </tbody>
  </table>
  </body>
  <script>
  function a1()
  {
    var val=a();

    console.log(val);
  }
      var mysql = require('mysql');


      const {app, BrowserWindow} = require('electron')
      const url = require('url')
      const path = require('path')


  function a(){
          var mysql = require('mysql');
          var h = new Object();
          // Add the credentials to access your database
          var connection = mysql.createConnection({
              host     : 'localhost',
              user     : 'root',
              password : null,
              database : 'last'// last is my database 
          });

          // connect to mysql
          connection.connect(function(err) {
              // in case of error
              if(err){
                  console.log(err.code);
                  console.log(err.fatal);
              }
          });

          // Perform a query
          $query = 'SELECT * FROM `customer`';

          connection.query($query, function(err, rows, fields) {
              if(err){
                  console.log("An error ocurred performing the query.");
                  console.log(err);
                  return;
              }

               console.log(rows)// i received the  outputted value
        return rows;       //but when i use return rows to other function
                           // result in undefined
          });

          // Close the connection
          connection.end(function(){
              // The connection has been closed
          });

      }

   </script>
</html>
dhanasekar
  • 3
  • 1
  • 8
  • 1
    This will not work because, you are trying to return `rows` from the `callback function`. Take a look here, [how to return values from callback functions](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function) – Madhavan.V Dec 07 '17 at 10:27
  • i found out by using promises i can get the value var val=h1; // with the promised values use the function to print the particular values val.then( // Log the fulfillment value function(val) { var size=val.length; for(var i=0;i{h=rows; resolve(h); }); }) – dhanasekar Dec 07 '17 at 12:41

0 Answers0