Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

connection.query(...).then is not a function

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

like image 874
Sammu Sundar Avatar asked Sep 05 '18 11:09

Sammu Sundar


2 Answers

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

like image 59
richard937 Avatar answered Sep 29 '22 01:09

richard937


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);
});
like image 43
Sagar Avatar answered Sep 29 '22 03:09

Sagar