How do I return the value of a query in the nodejs

Asked

Viewed 644 times

2

Well, I have the following code:

    pool.query('SELECT * FROM `info` WHERE `id` = 1', function(err, row) {

    var jogo = row[0].jogo;


    console.log(jogo);


    });

The problem is, if I take out the var game of the function, it no longer works, however I needed it to leave the function to do other checks outside the function.

How can I do that?

Thank you.

1 answer

2


The problem here is asymchronism. You have to use callbacks to invoke a function when this value has been returned from the database.

If you have the logic that needs it you have to chain things up like this:

function verificarJogo(jogo) {
  // aqui podes fazer as verificações que precisas
  console.log(jogo);
}

function buscaJogo(id) {
  var select = 'SELECT * FROM `info` WHERE `id` = ' + id;
  pool.query(select, function(err, row) {
    if (err) console.log(err);
    verificarJogo(row[0].jogo);
  });
}

buscaJogo(1);

Or do it in the style:

function verificarJogo(jogo) {
  // aqui podes fazer as verificações que precisas
  console.log(jogo);
}

function buscaJogo(id) {
  return new Promise(function(resolver, rejeitar) {
    var select = 'SELECT * FROM `info` WHERE `id` = ' + id;
    pool.query(select, function(err, row) {
      if (err) rejeitar(err);
      else resolver(row[0].jogo);
    });
  });

}

buscaJogo(1).then(verificarJogo);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.