Ceddy Ceddy - 6 months ago 9
Javascript Question

node js callback as var

Am trying to create a method that i can call from all parts of my express app, i simply pass a value to this method and it searches through mongodb using moongose to see if user exists, then it returns a Boolean as result.

function findUserExists(name){

User.findOne({ "name": name }, function(err, user) {

if (user){
console.log("user exits");
return true;
}
else{
console.log("user not exits");
return false; }
});


Now when i call it in another method like this, it doesn't return the Boolean value in time.

if (findUserExists("username")){

// redirect to dashboard
console.log("user exits");
res.redirect('/dashboard');
}
else {
// redirect to sign up page
console.log("user must sign up");
res.redirect('/signup');
}


So in this case the other functions run before getting the Boolean value from the findUserExists(), my question is how can i make this function return a value before other functions run, in a way that i can call it in an IF condition or even a var like this

var exists = findUserExists(name);

Answer

You are trying to force synchronous code on asynchronous function. Short answer is: you shouldn't do this

Convert your function to callback

function findUserExists(name, callback) {
    User.findOne({ "name": name }, function (err, user) {
        callback(user);
    });
}

and then use as this:

findUserExists("username", function (exists) {
    if (exists) {
        console.log("user exits");
        res.redirect('/dashboard');
    } else {
        console.log("user must sign up");
        res.redirect('/signup');
    }
});

You can use promises to code look more synchronous if you use node 4 and above.