Function returning 2 values - callback issue?

Problem

I am working on a push notification server (based on NodeJS) that stores data in a MS SQL database. One of the functions I need is to check if a device already has been registered in my database. I coded that like this - console information for debugging purpose:

function deviceExists(devicetoken, shopguid) {
    sql.connect(config, function(err) {

        if (err) {
            console.log('Error: ' + err);
        }
        else {
            var request = new sql.Request();
            request.query("select top 1 devicetoken from notifications where devicetoken='" + devicetoken + "' and shopguid='" + shopguid + "'", function(err, recordset) {
                if (err) {
                    console.log('Error: ' + err);
                }
                else {
                    console.log('Records: ' + recordset.length)
                    if (recordset.length === 0) {
                       console.log('recordset.length === 0, returning false device does not exist');
                       return false;
                    } else {
                       console.log('recordset.length !== 0, returning true device does exist');
                       return true;
                    }
                }
            });
        }

    });
    console.log("Something went wrong, return true");
    return true;
}

What happens is that I always get to return values. First the true from the end of the function and then the true or false from where I checked the recordset length. I think I am running into a callback issue, but I don't know how to solve it.

I spend too long to get this to work, it must be my limited JavaScript knowledge that is blocking me to get it to work. I hope someone can help.

Problem courtesy of: CrashingDutchman

Solution

Here's an example of using async function calls inside of your own functions:

function someFunc( data1, data2, callback ) {

    db.query("SELECT * FROM table1 WHERE id=?", [data1], function( err, results ) {
        callback( results );
    }); 

}

See what's happening there? My function, 'someFunc' won't return anything, it's up to the callback object (which is a function) to return the results after the db query inline-function callback is finished.

It's would be used like so:

someFunc( 32, 54, function ( results ) {
    // results contains the results of the db query
    results.forEach (...);
});
Solution courtesy of: Chris

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.