试图从数据库 [node js, mysql, promise] 中检索信息

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

这应该是访问本地主机数据库的简单连接。

重要信息:我已经尝试过非常相似的代码,即使不完全相同,但它确实有效。区别在于我没有将连接放在 class 变量 (this.connection) 中,但因为它不是异步的,所以我没有多想。所以也许这只是一个 javascript 语法相关的问题。任何提示将不胜感激。

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

您的代码中有两个问题:

  • 当您因错误而拒绝时,您不会return,而是继续该功能
  • 您在匿名非 lambda 函数中访问 this,这将覆盖 this

此版本修复了上述两个问题:

    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
    }