node.js - callback gets fired without waiting node js -


hi new node trying create sign functionality ... checks whether username exists or not , other few validations .. not waiting getting results mongodb check whether user exists or not.. callback fired early..pls how can make way 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 = [];      (var key in data) {          userdata.push(data[key]);      }      var nam = object.keys(data);        this.loginvalidate(userdata[0], function(data) {        //should wait 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);    }

this yet case of not understanding how callbacks , asynchronous routines work in javascript. functions not wait completion of asynchronous function. may wish read before continuing. here few related questions:

to solve particular problem, asynchronous calls loginvalidate, validatemobile , callback must chained respective callback functions. here's how (note approach fail-fast , not trigger more validation steps know user invalid):

exports.registervalidate = function(data, callback) {     var isvalid = true;     var userdata = [];     var errors = [];     (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());       });     }); } 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -