Asynchronous function return

Asked

Viewed 48 times

0

I am trying to return the value of a query using Sequelize but it always comes as Undefined. I imagine it is due to being an asynchronous function.

const { Sequelize, sequelize } = require('../../config/database');

// Classe para realizar manipulação dos usuarios no banco
class UserDAO{
    // Consultar registros no banco pelas credenciais passadas pelo controller
    userQuery(userCredentials){   
        sequelize.query(`SELECT * FROM usuarios WHERE login='${userCredentials.user}' AND senha='${userCredentials.pass}'`).then((result) => {
            return result;
        }).catch((err) => {
            console.log(err);            
        });
    }

}

module.exports = UserDAO;

The Userdao class is instantiated in another file and the userQuery() function is called by passing an object as argument. I need the userQuery() function to return the then() value of the sequelize.query().

  • try to give a console.log(result) and put here what appears in your log

  • Within the sequelize.query() function it shows the object that is returned by the query (how it should happen). That is, everything works perfectly well within the function, however when I try to externalize it somehow it gets Undefined.

1 answer

0


I’ll try to help you try to do it this way:

const { Sequelize, sequelize } = require('../../config/database');

// Classe para realizar manipulação dos usuarios no banco
function pesquisa() {
class UserDAO{
    // Consultar registros no banco pelas credenciais passadas pelo controller
    userQuery(userCredentials){   
        sequelize.query(`SELECT * FROM usuarios WHERE login='${userCredentials.user}' AND senha='${userCredentials.pass}'`).then((result) => {
            console.log(result)
            return result;
        }).catch((err) => {
            console.log(err);            
        });
    }

  }
}

pesquisa()

probably solve this, keep an eye to see the result of the log, if everything goes well export this function as an object JSON in that way:

    const { Sequelize, sequelize } = require('../../config/database');

    // Classe para realizar manipulação dos usuarios no banco
module.exports = {
pesquisa: function(){
class UserDAO{
        // Consultar registros no banco pelas credenciais passadas pelo controller
        userQuery(userCredentials){   
            sequelize.query(`SELECT * FROM usuarios WHERE login='${userCredentials.user}' AND senha='${userCredentials.pass}'`).then((result) => {
                console.log(result)
                return result;
            }).catch((err) => {
                console.log(err);            
            });
        }

      }
    }
}
  • Thank you very much man!

  • I’m glad I could contribute in some way, don’t forget to mark the answer as correct.

Browser other questions tagged

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