Connection. Query(. ..). Then Is Not a Function

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

1

3 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

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);
});

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!:)');
      }
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.