0

I am using a very simple function. A model file where i am querying and a controller file where i am using the model functions. controller.js function is like below

let handlers = async (request, h) => {


    let res = await users.checkUsers(request.payload);
    console.log("response --- ");
    console.log(res);

    
    if (res > 0)
        return h.response({
            message: 'This user is already exist please try with some other creds.'
        }).code(402)
 
    
    return h.response({
        message: 'Successfully created.'
    }).code(200)
}

And users.checkUser function is like below

let checkUsers = async (params) => {  

    sql.connect(config.dbConfig, function(err){
        if(err) console.log(err)
        let sqlRequest = new sql.Request();
        let query = "SELECT count(slNo) AS 'totalUser' FROM Users where email='" + params.email + "'";
        
        sqlRequest.query(query, function(err, data){
            if(err) return err;
            sql.close();
            console.log(data.recordsets[0][0].totalUser)
            return data.recordsets[0][0].totalUser;
            
        })
    })

}

Now if i console data.recordsets[0][0].totalUser i am able to see the result.However unable to return the response. When i try to access it in the users controller file i am able to see "undefined". Not sure what i missed

  • Currently `checkUsers` uses different approach to handling async actions: node callback or CPS. Just putting `async` infront of it won't magically make it to switch to promises. You need to promisify `sql.connect` and `sqlRequest.query` and await for their result. – Yury Tarabanko Aug 25 '20 at 10:37
  • 1
    This question contains detailed description on how to handle async actions in javascript. Reading it will likely help you to understand how to proceed in your case [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Yury Tarabanko Aug 25 '20 at 10:38
  • Marking a function as `async` (a) makes it return a promise and (b) allows you to `await` promises inside it. However, inside it you are calling functions with traditional callback APIs so `await` wouldn't work even if you were using it. – Quentin Aug 25 '20 at 10:42
  • **Danger**: [Your code is vulnerable to SQL injection](https://bobby-tables.com/) – Quentin Aug 25 '20 at 10:43

0 Answers0