6

I am new to the node js . I am using node with express in my backend and mysql as database . I have the confusion while handling the async calling . In my code while i use .

return connection.query(qry).then(
        function(result) {
          console.log('Query executed');
          resolve(result.rows[0]);
        },
        function(err) {
          console.log('Error occurred', err);
          reject(err);
        }
  )

I got error connection.query(...).then is not a function

connection.query(qry, function (err, rows, fields) {

});

is executed correctly. Simple query i am not getting any problem . while execute the complex query the above one is not wait for complete query execution

Sammu Sundar
  • 556
  • 3
  • 9
  • 24
  • I think Mysql.query is not a promise function. Mongo DB is and others but MySQL is no. See here: https://codeburst.io/node-js-mysql-and-promises-4c3be599909b – Nandostyle Apr 11 '20 at 00:53

3 Answers3

5

To use .then() with mysql first you need to “promisify” the database client.That can be done by creating a wrapper class for the MySQL client.
Check this article for better understanding

richard937
  • 199
  • 2
  • 3
  • 11
3

I have not found that, we can use promise with connection.query('') function. As per mysqljs documentation we can pass callback function for getting result.

var mysql      = require('mysql');
var connection = mysql.createConnection(...);

connection.query('SELECT * FROM table_name', function (error, results, fields) {
  if (error) throw error;

  console.log(result);
});
Sagar
  • 4,473
  • 3
  • 32
  • 37
2

You need to import mysql, and also actually create the connection.

Just do:

  var mysql=require('mysql');
    var connection=mysql.createConnection({
      host:'127.0.0.1',
      port: '3306',
      user:'root',
      password:'12345',
      database:'db'
    });

    connection.connect(function(error){
      if(!!error){
        console.log(error);
      }else{
        console.log('Connected!:)');
      }
    });
Menelaos
  • 23,508
  • 18
  • 90
  • 155