Frage

Having some trouble understanding callbacks, heres my code for authentication (via MySQL)

function authenticate(username, password, callback) {
    var query = "SELECT * from mydb.users where username='" + username + "'and BINARY password='" + password + "'";
    connection.query(query, function (err, rows) {
        if (rows[0] != undefined) {
            if ('username' in rows[0]) {
                if (rows[0].username == username) {
                    callback(true);
                }
            }
        }
        callback(false);
    });
};

exports.assets=function(req,res) {
    var username = req.param("username");
    var password = req.param("password");

    authenticate(username, password, function (didAuthenticate) {
        if (didAuthenticate) {
            console.log("Authenticated");
        }
        else {
            console.log("Failed");
        }
    }); 
};

Output when user/pass matches:

Authenticated
Failed

With no match:

Failed

How come the if/else statement doesn't work when didAuthenticate returns true?

War es hilfreich?

Lösung

Simply doing callback(...) does not end the execution of the function; you need a return statement to tell the function to stop running, as seen below:

function authenticate(username, password, callback) {
    var query = "SELECT * from mydb.users where username='" + username + "'and BINARY password='" + password + "'";
    connection.query(query, function (err, rows) {
        if (rows[0] != undefined) {
            if ('username' in rows[0]) {
                if (rows[0].username == username) {
                    return callback(true);
                }
            }
        }
        return callback(false);
    });
};

You will see this technique used when you read other NodeJS code.

Andere Tipps

Instead of using a return statement to terminate you could put an else statement for your failure condition.

function authenticate(username, password, callback) {
    var query = "SELECT * from mydb.users where username='" + username + "'and BINARY     password='" + password + "'";
    connection.query(query, function (err, rows) {
        if (rows[0] != undefined && rows[0].username === username) {
            callback(true);
        }
        else {
            callback(false);
        }
    });
};
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top