Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return value from callback in node.js and mongoose

I tried the following code.

function authenticate( accesskey )  {
    var res = someModel.findOne( {'uid': accesskey},  function ( err , user) {
          if(err){
              console.error("Can't Find.!! Error");
          }
          if(user===null){
              return false;
          }
          else{
          console.log(user);
          return true;
          }
    });
    console.log(res);
    return res;
}

but res here returns a mongoose data type.

I wish to call the authentication function like this -

if(authenticate(req.params.accesskey)){
//do something
}
else{
//do something else
}

UPDATE after implementing SOLUTION from Mustafa Genç

After getting comfortable with callbacks I ended up with the following code.

function authenticate( req, result, accesskey, callback )  {
    var auth = null;

    someModel.findOne( {'uid': accesskey},  function ( err , user) {
          console.log("try authenticate");
          if(err){
              console.error(err);
          }
          if(user===null) 
              auth = false;
          else 
              auth = true;
          callback(auth);
    });
}

And I use it like this -

routeHandler( req, reply ) {
      authenticate( req, reply, req.params.accesskey , function (auth) {
          if(auth) {

              //"primary code"

          } 
          else {
              //fallback
          }
      });
  }
like image 483
rahulroy9202 Avatar asked Dec 15 '22 01:12

rahulroy9202


2 Answers

You need a callback function since this is an async request:

function authenticate(accesskey, callback)  {
    var auth = null;

    userModel.findOne({'uid': accesskey}, function(err, user) {
        console.log("TRY AUTHENTICATE");

        if (err) {
            console.error("Can't Find.!! Error");
        }

        //None Found
        if (user === null) {
            console.error("ACCESS ERROR : %s  Doesn't Exist", accesskey);
            auth = false;
        } else {
            console.log(user);
            auth = true;
        }

        callback(auth);
    });
}

And call this function like :

authenticate("key", function (authResult) {
    //do whatever
});
like image 195
Mustafa Genç Avatar answered Jan 02 '23 19:01

Mustafa Genç


You can also try with promises.

function authenticate( accesskey )  {
    var promise = someModel.findOne({'uid': accesskey}).exec();
}

routeHandler( req, reply ) {
      authenticate(req.params.accesskey)
      .then(function (auth) {
          if(auth) {
              //"primary code"
          } 
          else {
              //fallback
          }
      })
      .catch(console.error);
  }
like image 25
Anastasios Andronidis Avatar answered Jan 02 '23 19:01

Anastasios Andronidis