-1

I am new to node js and I am stuck with nested callback.

I want callback to be executed first and then only line after callback needs to be executed.

Here is my sample code :

signup: function (req, res) {

    var user = UserModel.checkIfDataExists({email: req.body.email, isAccountVerified: 1}, function (user) {

        //console.log(user);
        var mobileUser = UserModel.checkIfDataExists({mobileNumber: req.body.mobileNumber, 'country.code': req.body.countryCode, isAccountVerified: 1}, function (mobileUser) {
            console.log(mobileUser);
        });
    });
    res.send('Success');
}

Here is helper function :

checkIfDataExists: function (value, callback) {
    User.findOne(value)
        .exec(function (err, result) {
            if (err) {
                log('Error in Login With Mobile API : ', err.message);
                callback(false);
            } else {
                callback(result);
            }
        });
}

Upon executiong current code, I am getting null in console as line is executed(commented console.log(user)) and after that callback is returning while if I print console for outer callback then it is able to print that in log. Inner callback is not working.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

You need to call the callback with an error if there is an error.

When you call callback(false); then the callbacke things there was no error (it's false) and it tries to get the second argument (which is not defined).

So instead of:

    .exec(function (err, result) {
        if (err) {
            log('Error in Login With Mobile API : ', err.message);
            callback(false);
        } else {
            callback(result);
        }
    });

you should use something like:

    .exec(function (err, result) {
        if (err) {
            log('Error in Login With Mobile API : ', err.message);
            callback(err);
        } else {
            callback(null, result);
        }
    });

or in this case it can be made shorter:

    .exec(function (err, result) {
        if (err) {
            log('Error in Login With Mobile API : ', err.message);
        }
        callback(err, result);
    });

Some other way to do it with custom error and using early return to avoid the else:

    .exec(function (err, result) {
        if (err) {
            log('Error in Login With Mobile API : ', err.message);
            callback(new Error('Custom error'));
            return;
        }
        callback(null, result);
    });

Node traditionally uses the error-first callback convention. See this for more info:

rsp
  • 107,747
  • 29
  • 201
  • 177
  • Dude that portion is working fine though I appriciate changes you told, I want to know why my second callback is not giving any output while first callback is printing the things – Nirav Majethiya Jul 14 '17 at 03:03