Lothar
Lothar

Reputation: 3489

Making a database call inside a node function

I have a function that I am calling and I need to make some database queries inside of that function. What is the best way to do this in node? Currently I just make a request and assign the return value to a variable but this results in the variable not being set. Example:

// bunch of code
var is_member = false;
mysql.query('SELECT EXISTS ( SELECT * FROM `qazusers` WHERE `qazemail` = ? OR `otheremail` = ? LIMIT 1)', [emailaddress, emailaddress], function (err, result) {
    if (err) {
        logger.info('Error checking. ', err);
    }
    logger.info('checkmembership: ', result);
    if (result[0] === 1) {
        is_member = true;
    }
// bunch more code finishing out the function this is inside

Once the containing function is done running, is_member is always false. I assume this is due to the asynchronous nature of node but, what is the best way to handle this? I have read up a bit on Promises (like the Q library) but I am still not sure of the best way to handle setting a variable inside of a nodejs based function. How would this be done, ideally?

Upvotes: 1

Views: 300

Answers (1)

Bergi
Bergi

Reputation: 665455

Promises are a fine approach. You'd use them like this:

var promise = Q.ninvoke(mysql, "query", 'SELECT EXISTS ( SELECT * FROM `qazusers` WHERE `qazemail` = ? OR `otheremail` = ? LIMIT 1)', [emailaddress, emailaddress])
var moreresults = promise.then(function(result) {
    logger.info('checkmembership: ', result);
    return result[0] === 1;
}).then(function(is_member) {
    // bunch more code finishing out
    return more;
});
moreresults.catch(function(err) {
    logger.info('Error checking. ', err);
});

Upvotes: 2

Related Questions