Function returning Undefined

Asked

Viewed 122 times

0

Função retornando undefined

Function returning Undefined, do not know what to do

  • Please click on [Edit] and put the code as text. Putting it as an image is not ideal, understand the reasons reading the FAQ.

1 answer

0


Take some of your time to read to read about How not to ask questions.

What you need is to return one Promise of the method getUserById, example based on the code you posted:

function getUserById(id){
  return new Promise((resolve, reject) => {
    sql.connect((err) => {
      if(err)
        return reject(err);
        
      sql.query('SELECT * FROM users WHERE id = ?', [id], (error result, fields) => {
        if(error)
          return reject(error);
          
        return resolve(result);
      }
    });
  });
}

Note the differences between the above code and what you wrote:

  • getUserById takes as parameter only the id and returns a precedent that can be solved or rejected in case of errors (it is important to consider possible errors)

  • NEVER, but NEVER even enter the value of a variable directly into the query body, use the escape (?) and pass the value of the variables as an array in the second function parameter.

  • The third parameter of the method query is a function that will be called when your query returns some result.

But look how ugly this code is above, every time you do a query you open a connection to the DB that by the way was never closed, the code full of callbacks, since it was not specified in the question which module you are using, I recommend using the Mysql Promise, that will greatly facilitate the use of the Precedents in your queries, same example above but written better:

const db = require('mysql-promise')();

// Inicializa a conexão com o database
db.isConfigured() || db.configure(DB_CONFIGURATIONS_HERE);

const getUserById = (id) => db.query('SELECT * FROM users WHERE id = ?', [id]);

Or as I do in my projects, I create a module that is only concerned with making the connection to the Database and queries so that it can be used in different parts of the application, example:

const db = require('mysql-promise')();

// Inicializa a conexão com o database
db.isConfigured() || db.configure(DB_CONFIGURATIONS_HERE);

module.exports = {
  shutdownPool: () => db.end(),
  
  getUserById = (id) => db.query('SELECT * FROM users WHERE id = ?', [id]),
}

And to call any of the above methods just do:

getUserById(1)
.then((resultado) => { ... tudo funcionou e você tem uma resposta })
.catch((error) => {... algo deu errado})

Or simply:

try{
   const resultado = await getUserById(1);
   // Tudo ok, faça algo com o resultado

}catch(error){
   // Algo deu errado
}
  • Brabíssimo, thx

Browser other questions tagged

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