0

I am trying to simply update a global variable within a function but am running into an issue. Its simply not updating and firing the code below as result.

The results for console.log(duplicates) seem to be in wrong order which Im assuming is the cause of the problem.

This is in AngularJS, but I dont think this is related to the problem

Expected output in console when a user is found:

1

0

Output Im getting:

0

1

module.exports.register = function (req, res) {
    var duplicates = 0;
    var user = new User();
    user.name = req.body.name;
    user.email = req.body.email;
    user.cro = req.body.cro;
    user.companyname = req.body.companyname;

    user.setPassword(req.body.password);

    // first, check that this email address has not been registered before
    User.findOne({email: req.body.email}, function (err, user) {

        // Return if user not found in database
        if (!user) {
            console.log('great, no user was found, we may carry on');
        } else {
            res.status(401).json({
                "error": "This email address has already been registered."
            });
            duplicates = 1;
            console.log(duplicates);
        }

    });
    console.log(duplicates);

    if (duplicates == 0) {
        /* Fire this code if this duplicates has not updated to 1 */
    }

};
Adrian
  • 1,976
  • 5
  • 41
  • 105
  • 1
    Also, that's not a global variable. – melpomene Dec 30 '16 at 14:43
  • 1
    The behavior is correct. `duplicates` is updated in a callback defined inside `findOne` function. I assume that the function is making server side call and hence it will be invoked, after the response has been received. Prior to that the duplicates will be printed with value as 0 and later, when callback is invoked, duplicates is updated to 1. – CuriousMind Dec 30 '16 at 14:46

0 Answers0