简体   繁体   中英

Make synchronous MySQL queries in NodeJS

I have been doing google searches for 5 days, I hope to find the solution ... I know that it does not work because it is asynchronous, but I need the program (it is a Discord bot) to respond with a data that I get from a DB. I have tried Promises and callbacks, but I do not know if it is because I am a novice with asynchronous, that nothing works for me.

        const con = mysql.createConnection({
            host: datos.host,
            user: datos.user,
            password: datos.password,
            database: datos.database
        });

        function leerPromesa() {
            var promise = new Promise(function (resolve, reject) {
                con.query('SELECT * from ranking;', function (err, rows, fields) {
                    if (err) {
                        reject(err);
                        return
                    }

                    resolve(rows);
                    rows.forEach(element => console.log(element));

                })
            });

            return promise;
        };


        var promesa = leerPromesa();
        promesa.then(
            function (rows) {
                rows.forEach(element => msg.reply(element));
            },
            function (err) {
                msg.reply(err);
            }
        );

        con.end();

What the bot does is respond with blank text.

First, you're not really connecting to database.

If you refer to docs https://github.com/mysqljs/mysql :

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

// then connect method
connection.connect();

So your code will never work..

Second, you are closing connection before any query execution:

con.end();

Correct is to close connection after leerPromesa function execution.

Finally, code could look something like this:

const con = mysql.createConnection({
  host: datos.host,
  user: datos.user,
  password: datos.password,
  database: datos.database
});

con.connect();

function leerPromesa() {
  return new Promise(function(resolve, reject) {
    con.query("SELECT * from ranking;", function(err, rows, fields) {
      if (err) {
        return reject(err);
      }
      return resolve(rows);
    });
  });
}

leerPromesa()
  .then(
    function(rows) {
      rows.forEach(element => msg.reply(element));
    },
    function(err) {
      msg.reply(err);
    }
  )
  .finally(function() {
    con.end();
  });

I used finally method on Promise to close connection in every situation https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM