Skip to content
Advertisement

Trying to retrieve information from a db [node js, mysql, promise]

This is supposed to be a simple connection to access a localhost database.

Important information: I’ve tried very similar code, if not the exact same, and it works. The difference is I didn’t put the connection in a class variable (this.connection) but because it’s not async I didn’t think much of it. So maybe it’s simply a just javascript syntax related issue. Any tips would be greatly appreciated.

class Request {
    constructor(connection) {
      this.connection = mysql.createConnection(connection);
    }   // The parameter that gets passed is a dictionary { host: 'xxx', user: "xxx" ...


    sendMessage(message) {
        let arr = message.content.substring(1,message.length).toLowerCase().split(' '); // unimportant
        arr = arr.filter(function (el) {return el != '';}); // unimportant

        const promise = new Promise((resolve, reject) => {
            this.connection.connect(function(err) {
                console.log(this.connection);  // This returns a description of the connection just fine
                  if (err) reject(err);        // No error fires here
                      console.log(this.connection);   // WHERE THINGS GO WRONG: Nothing gets printed on the console
                      this.connection.query('SELECT * FROM categories;', function (err, rows, fields) {
                          if (err) reject(err);       // No error fires here
                          resolve(rows);
                      });
                  });
              });
          
        promise.then((result) => console.log(result));   // Nothing fires here either

Advertisement

Answer

There were two problems in your code:

  • When you reject with an error, you don’t return, but continue the function
  • You were accessing this in anonymous non-lambda functions, which would overwrite this

This version has fixes for the above two issues applied:

    sendMessage(message) {
        let arr = message.content.substring(1, message.length).toLowerCase().split(' '); // unimportant
        arr = arr.filter(function (el) { return el != ''; }); // unimportant

        const promise = new Promise((resolve, reject) => {
            this.connection.connect((err) => { // Using arrow function to keep original `this`
                if (err) return reject(err); // If there's an error, return!
                this.connection.query('SELECT * FROM categories;', function (err, rows, fields) {
                    if (err) return reject(err); // Again, if there's an error, return!
                    resolve(rows);
                });
            });
        });

        promise.then((result) => console.log(result));   // Nothing fires here either
    }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement