Amarnath
Amarnath

Reputation: 8865

NodeJS callback: How to make the call wait for mongodb query result

I have a registration dialog where when the user enters username and password I need to check the DB whether the user is present or not. But when I am validation for the same my call does not hold back until I get the results from the server.

After searching for a while I got to know about callbacks. So I have added a call back inside this.isUser method. And it is successful. But now doRegistration method is not synchronous with the isUser method.

How to make all my calls synchronous?

this.doRegistration = function(uname, pwd, confirmPwd) {
    if(this.isUser(uname)) {
        return "USER_EXISTS";
    } else {
        saveUser(uname, pwd);
        return "SUCCESS";
    }
};

this.isUser = function(username) {
    var users = new Array();
    getAllUsers('param', function(response) {
        users = response;
        console.log(users.length);
        for(i = 0; i < users.length; i++) {
            if(users[i].username === username) {
                return true;
            }
        }
        return false;
    });
};

function getAllUsers(param, callback) {
    loginFactory.AllUsers.query(function(response) {
        if(response != undefined && response.length > 0) {
            callback(response);
        }
    });
}

Upvotes: 0

Views: 994

Answers (1)

Sarath Nair
Sarath Nair

Reputation: 2868

You may rewrite the code like following:

this.doRegistration = function(uname, pwd, confirmPwd, callBack) {
        this.isUser(uname,function(flag) {
          if(flag){
            callBack("USER_EXISTS");
          }
          else {
            saveUser(uname, pwd, function(err,result){
               if(err){
                  callBack("SAVING_FAILED");
               }
               else {
                  callBack("SUCCESS");
               }
            });
          }
        });
    };

    this.isUser = function(username,callBack) {
        var users = new Array();
        getAllUsers('param', function(response) {
            users = response;
            console.log(users.length);
            for(i = 0; i < users.length; i++) {
                if(users[i].username === username) {
                    callBack(true);
                }
            }
            callBack(false);
        });
    };

    function saveUser(userName, pwd, callBack){
        //code to save user
        //chek for error in saving
        if(err){
          callBack(err,null)
        }
        else {
          callBack(null, "success")
        }
    }

    function getAllUsers(param, callback) {
        loginFactory.AllUsers.query(function(response) {
            if(response != undefined && response.length > 0) {
                callback(response);
            }
        });
    }

You may also define saveUser as a function with callback. Here it wont wait for saveUser method to complete.

Upvotes: 1

Related Questions