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?
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.
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.
When a callback function completes execution, it returns any return value that it might have to the DataBlade API, which invoked it.
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.
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');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With