0

I am trying to refactor some inherited code. In every endpoint was the same validation code. I want to pull it out into it's own method. I am new to promises, but I think that is what I want to use. The issues is prom seems to be resolved at the User.findOne call and exits with an undefined prom.promise.

cheers bob

function validateUser(req) {
    var prom = q.defer();
    var token = getToken(req.headers);
    if (token) {
        console.log("have a token")
        var decoded = jwt.decode(token, config.secret);
        console.log("now going to look for the user")
       //Problem exit is on next line
        User.findOne({
            name: decoded.name
        }, function (err, user) {
            if (err) throw err;
                prom.reject(err);
            if (!user) {
                console.log("no user found")
                prom.reject("Authentication failed. User not found.")

            } else {
                console.log("user found returning true")
                prom.resolve(true);

            }
        })

    } else {
        console.log("no token found")
        prom.reject("No token provided.")
    }
    return prom.promise;
}
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
Bob Cummings
  • 412
  • 8
  • 15
  • 1
    Don't fall for the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it). Mongoose already returns promises when you don't pass a callback. – Bergi May 01 '17 at 17:16

1 Answers1

0

why you are using promises when mongoose itself returns it.

function validateUser(req, callback) {
var token = getToken(req.headers);
if (token) {
    var decoded = jwt.decode(token, config.secret);
    User.findOne({
        name: decoded.name
    }, function (err, user) {
        if (err) throw err;
            callback(err);
        if (!user) {
            callback("Authentication failed. User not found.")

        } else {
            console.log("user found returning true")
            callback(null, {status:true, userData:user});
        }
    })

} else {
    callback("No token provided.")
}
}

In above code,

if token is not found callback is returned with an error in the first attempt. if token is found then it is decoded in a row and if matched in DB if the result is an error then the callback is called with err parameter else if no user is found or empty match then a custom message is sent in callback error part. But in final is returned as success with status and userData.

Amulya Kashyap
  • 2,333
  • 17
  • 25
  • 1
    Thank you very much, I knew Mongoose was returning a promise, I just could not make the leap to using it. Again thanks very much. – Bob Cummings May 01 '17 at 20:11
  • −1 for recommending a function that takes a `callback` parameter and does not return a promise. – Bergi May 01 '17 at 22:08