How do I return the value of a query in nodejs

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 the var game from the function, it no longer works, however I needed it to exit the function to do some other checks outside the function.

How can I do this?

Thank you.

    
asked by anonymous 26.03.2017 / 04:26

1 answer

2

The problem here is asynchronous. You must use callbacks to invoke a function when that value has been returned from the database.

If you have logic that needs it you have to chain things 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 the promises 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);
    
26.03.2017 / 09:48