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

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

重要信息:我尝试过非常相似的代码,如果不是完全相同的话,它也能工作。不同之处在于我没有将连接放在类变量 (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
cc4400092 回答:试图从数据库 [node js, mysql, promise] 中检索信息

您的代码中有两个问题:

  • 当您因错误而拒绝时,您不会返回,而是继续执行该功能
  • 您在匿名非 lambda 函数中访问 def fn2(x): return x,(3*x,x**2) # actually output is a tuple of int and tuple >>> x,(a,b) = fn2(2) # unpacking (2,(6,4)) >>> x,a,b (2,6,4) ,这会覆盖 this

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

this
本文链接:https://www.f2er.com/63677.html

大家都在问