Javascript with async-await

Asked

Viewed 34 times

-2

I am using async-await in the SQL query function in the Model and I use the MVC standard. The problem is that when executing the function (select SQL) in the model it is executed but the return is: [Object Object] as if the result were undefined. The application shows no error but does not go back to the controller where I have another console.log to monitor the return. Below part of the code.

Routes.js file

const segurosRoutes = require('../controllers/segurosControllers.js');

module.exports = (app) => {
    app.get('/estagio/movimentacoes/cadastroSeguros', segurosRoutes.segurosGetAll);
}

controllers.js file

const segurosController = require('../models/segurosModels.js');
 
module.exports = {
    segurosGetAll,
}


function segurosGetAll(req, res){
    console.log("Entrando em Controllers Seguros: ")
    segurosController.getAll(function (err, result){
        if(err) {
            console.log("Erro: " + err)
            throw err;
        }else{
            console.log("Resultado "+result)            
        }
    })
}

models.js file

const client = require('../../config/conexao.js');
 
const moment = require('moment');

module.exports = {
  getAll,
}  
 
async function getAll() {

  m_sql = 'select A.*, B.seg_razaosocial, B.seg_nomefantasia, C.alu_nome, D.usu_username from seguros A left join seguradora B on A.seg_codigo = B.seg_codigo left join usuarios D on A.usu_codigo = D.usu_codigo left join alunos C on A.alu_codigo = C.alu_codigo ';

  console.log("SQL em Seguros...."+m_sql)
  console.log("-----------------------")
  let retorno

  try{
    const retorno = await client.query(m_sql)
    console.log("Retornando da SQL: "+retorno)
  } catch(erro) {
    console.log(erro)
    retorno  = erro
  }

  return retorno

}

In the terminal:

Express executando na porta. 3000
Entrando em Controllers Seguros: 
SQL em Seguros....select A.*, B.seg_razaosocial, B.seg_nomefantasia, C.alu_nome, D.usu_username from seguros A left join seguradora B on A.seg_codigo = B.seg_codigo left join usuarios D on A.usu_codigo = D.usu_codigo left join alunos C on A.alu_codigo = C.alu_codigo 

Returning from SQL: [Object Object]

  • 5

    Do not create duplicate questions from one that has already been closed (MVC Javascript+async await). Prefer to improve the original question than open another.

1 answer

-3

When javascript returns [Object Object] it is because it is printing the object instance. To solve this, you can use the JSON.stringify() method to show the contents of your variable, so it converts your object into a string.

In that case it would be: console.log("Returning from SQL: "+ JSON.stringify(return))

Browser other questions tagged

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