7
votes

I am building an application in which on a particular call, i must block and wait for the results from an authentication query before coninuing.

function authenticate(userid, hash)
{
    mysql_client.query("SELECT `hash` FROM `auth` WHERE `userid` = " + userid, function selectCb(err, results, fields) {
    if (err)
    {
      client.send("Error communicating with mysql, please retry your request");
      return false;
    }

    if(results.length == 0 || results[0].hash != hash)
    {
        client.send("Error comparing authentication data with database, please retry request");
        return false;
    }

    return true;
}
);
}

I want to be able to return those values from the authenticate() function itself, not the internal anonymous function selectCb and have authenticate block until the callback is complete. How can I go about doing this?

1

1 Answers

13
votes

Your outer function needs to provide a callback itself which can be executed once the mysql call is done. Something along the lines of this:

function authenticate(user, pass, callback) {
    mysql_client.query("...", function (err, results, fields) {
        if (err) {
            callback("Error communicating ...");
        } else if (results.length ...) {
            callback("Error comparing authentication...");
        }
        callback()
    });
});

Example usage:

authenticate('jim', '123456', function (err) {
    if (err) {
        alert(err);
    } else {
        alert('Welcome');
    }
});