2

I have the following code on a file called utils.js:

class functions {
validateUser(userId, userKey, sessionKey, plId) {
        let response = {
            validated: false,
            isAdmin: false,
            isCorporate: false
        }
         sql.connect(process.env.DB_CONNSTRING, function (err) {
            if (err) { msg.success = "0"; msg.message = "ERR_04: Could not connect to server."; res.json(msg); return; };
            let sqlString = `SELECT userLevel FROM dbo.users WHERE (userId =@userId) AND (userKey = @userKey) 
            AND (sessionKey = @sessionKey) and (plId = @plId)`
            let request = new sql.Request();
            request.input('userId', sql.Int, userId);
            request.input('userKey', sql.NVarChar, userKey);
            request.input('sessionKey', sql.NVarChar, sessionKey);
            request.input('plId', sql.Int, plId);
            request.query(sqlString, function (err, results) {
                if (err) { msg.success = "0"; msg.message = "ERR_07: Could not connect to server."; res.json(msg); return; };
                if (results.rowsAffected[0] != 0) {
                    response.validated = true;
                    if (results.recordset[0].userLevel == 1 || results.recordset[0].userLevel == 10) {
                        response.isAdmin = true;
                    };
                    if (results.recordset[0].userLevel == 10) {
                        response.isCorporate = true;
                    };
                    return (response);
                }
                else {
                    return (response);
                };
            });
        });
    };
}
module.exports = { functions };

Which is basically to validate if the logged user has the right credentials.

From a second .js file, I am requiring this file:

const utils = require('../utils/utils')
const functions = new utils.functions;

and then, on the router.post Im calling validateUser like this:

let AuthUser = async () => {
        const string = await functions.validateUser(payload.body.credentials.userId, payload.body.credentials.userKey, payload.body.credentials.sessionKey, payload.body.credentials.plId);
        return string;
    };
let isValid = AuthUser();
console.log(isValid)

But instead of getting the expected values on the console, I get

Promise { <pending> }

I tried making validateUser async but I still get the same results.

The idea is to continue running code after I get and process the results from validateUser

Any help will be appreciated.

Thanks.

1 Answer 1

3
class functions {
  validateUser(userId, userKey, sessionKey, plId) {
    return new Promise((resolve, reject) => {
      try {
        let response = {
          validated: false,
          isAdmin: false,
          isCorporate: false
        }
        sql.connect(process.env.DB_CONNSTRING, function (err) {
          if (err) throw err
          let sqlString = `SELECT userLevel FROM dbo.users WHERE (userId =@userId) AND (userKey = @userKey) AND (sessionKey = @sessionKey) and (plId = @plId)`
          let request = new sql.Request();
          request.input('userId', sql.Int, userId);
          request.input('userKey', sql.NVarChar, userKey);
          request.input('sessionKey', sql.NVarChar, sessionKey);
          request.input('plId', sql.Int, plId);
          request.query(sqlString, function (err, results) {
            if (err) {
              msg.success = "0"; msg.message = "ERR_07: Could not connect to server.";
              res.json(msg);
              resolve(res)
            } else {
              if (results.rowsAffected[0] != 0) {
                response.validated = true;
                if (results.recordset[0].userLevel == 1 || results.recordset[0].userLevel == 10) {
                  response.isAdmin = true;
                };
                if (results.recordset[0].userLevel == 10) {
                  response.isCorporate = true;
                };
              }
              resolve(response)
            }
          });
        });
      } catch (err) {
        reject(err)
      }
    })
  };
}

let AuthUser = () => {
  return new Promise(async (resolve, reject) => {
    try {
      const string = await functions.validateUser(payload.body.credentials.userId, payload.body.credentials.userKey, payload.body.credentials.sessionKey, payload.body.credentials.plId);
      resolve(string)
    } catch (err) {
      reject(err)
    }
  })
};
let isValid = await AuthUser();
console.log(isValid)

its console.logging the response that hasnt finished firing yet

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks Alilland... Ii tired your code, and I get "undefined"
I was getting undefined before too.. I need to get the response, so I can process the next steps on the code. Thanks Alilland :)
updated, give it a shot - if thats still returning undefined, i'll look harder at validateUser
I got await is only valid in async function, but validateUser is actually async :-/ this is so hard... lol...
in old style javascript, developers would use callbacks to write database calls - these got to be horrible and read very ugly. a common phrase used was getting stuck in "callback hell" because code just got to be so nested and layered. Promises were added do deal with the issue of async. A good rule of thumb is any time you are making a REST API query or a database call, wrap the function in a promise and make the exit point of the function either a reject or resolve.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.