Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeJS return value from callback

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?

like image 574
majic bunnie Avatar asked Mar 10 '12 23:03

majic bunnie


People also ask

What is the difference between promise and callback?

A callback function is passed as an argument to another function whereas Promise is something that is achieved or completed in the future. In JavaScript, a promise is an object and we use the promise constructor to initialize a promise.

Which callback function is passed the returned data?

The function to which the callback is passed is often referred to as a higher-order function. Conversely, Higher-Order Functions operate on other functions by either taking them as arguments or by returning them.

Can callback function return a value?

When a callback function completes execution, it returns any return value that it might have to the DataBlade API, which invoked it.

How do you return a call back?

Spell your name and provide a phone number, as well as information about why you're calling. Specify that you're returning the interviewer's call so that your call is given suitable priority. If you leave a voicemail instead, speak slowly and clearly, providing your name twice and giving your callback number.


1 Answers

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');
    }
}); 
like image 63
nickf Avatar answered Sep 30 '22 23:09

nickf