Home > Net >  Trying to return true or false from an authentification function with node
Trying to return true or false from an authentification function with node

Time:02-17

I have an async function that should return true or false. I know for sure that in this case it should return true but a console.log displays " Promise { pending }".

Here is the function :

const sql = require('mssql');
const sqlConfig = {
    
    user: accessDB.DB_USER,
    password: accessDB.DB_PWD,
    database: accessDB.DB_NAME,
  server: accessDB.SERVER,
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: false, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}
const authentification = async (login, password) => {

var sqls = `SELECT CLICOD FROM Clients WHERE CLICOD = '${login}' AND PasswordFtp ='${password}'`

 try {

  await sql.connect(sqlConfig)
  const result = await sql.query(sqls)

if (result.rowsAffected > 0) {
    return true;
}else {
    return false;
}

 } catch (err) {
console.log(err)
 }
}
module.exports = authentification;

This next part of the code is supposed to receive the result (true or false) but always ends up in the "not authorized" section even though a console.log of the result.rowsAffected does return 1.

app.get('/test',(req,res)=>{
 
if (authentification(req.query.login, req.query.pass)===true) {

  res.send("authorized");
}else {
  res.send("not authorized");
}

})

Can an async function return a result at all? Thank you for your help.

CodePudding user response:

change your route function to async and await for authentification response like below:

app.get('/test', async (req, res) => {
  const isAuthenticated = await authentification(req.query.login, req.query.pass)
  if (isAuthenticated === true) {

    res.send("authorized");
  } else {
    res.send("not authorized");
  }

})

CodePudding user response:

This does seem like an async/await problem. To await a condition that takes time to execute, you must use the await command before the function call. In order to use the await command, you must dignify the function the await is inside of to 'async'. This is how I would do it:

app.get('/test',async (req,res)=>{
    const isAuthenticated = await authentification(req.query.login, req.query.pass);

    if (isAuthenticated===true) {
      res.send("authorized");
    }else {
      res.send("not authorized");
    }
})

  • Related