0

Hi i am new to node i am trying to create sign up functionality ... it checks for whether username exists or not and other few validations .. but it is not waiting for getting results from mongodb to check whether user exists or not.. callback is fired very early..pls help how can i make it the way i want

var fs = require('fs');
var bcrypt = require('bcrypt-nodejs');
var util = require('./util');
exports.loginValidate = function(user, callback) {
    var User = require("../Models/UserSchema").model('User');
    User.findOne({
        uname: user
    }, function(err, userData) {
        if (err) console.log(err);
        callback(userData);
    });



}
exports.createUser = function(data, callback) {

    var User = require("../Models/UserSchema").model("User");
    var user = new User(data);
    user.save(function(error) {
        if (error) {

            return res.json({
                msg: "error"
            });
        } else {

            callback(true);
        }


    });

}
exports.registerValidate = function(data, callback) {
    var isValid = true;
    var userData = [];
    var errors = [];
    for (var key in data) {
        userData.push(data[key]);
    }
    var nam = Object.keys(data);

    this.loginValidate(userData[0], function(data) {
      //should wait for results
        if (data) {
            isValid = false;
        }
    });
  
    util.validateMobile(userData[2], function(bool) {
        if (!bool)
            isValid = false;
    });
    if (util.validateEmail()) {
        isValid = false;
    }
   //gets fired without waiting
    callback(isValid);

}
Rohit
  • 17
  • 7

1 Answers1

1

This is yet another case of not understanding how callbacks and asynchronous routines work in JavaScript. Functions do not wait for the completion of an asynchronous function. You may wish to read about it before continuing. Here are a few related questions:

To solve your particular problem, asynchronous calls to loginValidate, validateMobile and callback must be chained into their respective callback functions. Here's how I would do it (note that this approach is fail-fast and will not trigger more validation steps as soon as we know that the user is invalid):

exports.registerValidate = function(data, callback) {
    var isValid = true;
    var userData = [];
    var errors = [];
    for (var key in data) {
        userData.push(data[key]);
    }
    var nam = Object.keys(data);

    this.loginValidate(userData[0], function(data) {
      if (data) {
        callback(false);
        return;
      }

      util.validateMobile(userData[2], function(bool) {
        callback(bool && !util.validateEmail());
      });
    });
}
Community
  • 1
  • 1
E_net4
  • 27,810
  • 13
  • 101
  • 139