0

I have this script

This function check if the user session is stored in DB

function check_auth(input_session){
    var queryRes=false;
    var sql = "SELECT id_user FROM users_session WHERE session_id = " + connection.escape(input_session);
    connection.query(sql, function(err, results) {
        if (err) callback(err);
        if (results.length  > 0) {
            console.log(results.length);
            queryRes=true;
        }
    });
    return queryRes;
}

If return true the script continue and connect users to server

socket.use(function(socket, next) {
      var handshakeCookie = cookie.parse(socket.request.headers.cookie);
      var res=check_auth(handshakeCookie.sessionid);
      console.log(res);
    if (res===true) {
        next();
    }else{
        next(new Error('not authorized'));  
    }
});

The problem is that

console.log(results.length);

returns 1 so the result is true but

console.log(res);

returns false because the first function is executed before the query result. I dont want to know why this is happening, i know it, I want know how fix it in this script?

Alberto Alibaba
  • 305
  • 3
  • 17
  • Also related: [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Jonathan Lonowski Dec 10 '14 at 23:02
  • `connection.query()` is asynchronous, meaning it operates in its own time unbound from `check_auth()`. The `results` don't become available to modify `queryRes=true` until after `return queryRes` has already executed. – Jonathan Lonowski Dec 10 '14 at 23:05
  • @JonathanLonowski Lonowski I know it but how fix it? – Alberto Alibaba Dec 10 '14 at 23:07
  • There are a few possible solutions, all well discussed in the linked Q&As. One option in short would be to redefine `check_auth` to accept and call a `callback` argument instead of `return`ing, then use it as `check_auth(handshakeCookie.sessionid, function (err, res) { ... });`. It already has some of that implementation -- `if (err) callback(err);`. – Jonathan Lonowski Dec 10 '14 at 23:16
  • @JonathanLonowski that's just what I can not understand you give an example please? – Alberto Alibaba Dec 10 '14 at 23:19

0 Answers0