0

I have a module that search documents inside mongodb. When I call the check_permitions (with the argument), I get "undefined" return from the function, but the console.log(rslts[0].faq) return the right object. What is the problem?

var iapp = require('./app');

exports.check_permitions = function(user_id) {
  iapp.website_coll.find({}).where('admins_id').equals(user_id).exec(function(err, rslts) {
    if (err) {
      console.log(err);
    } else if (rslts) {
      console.log(rslts[0].faq);
      return (rslts[0].faq);
    } else if (!rslts) {
      console.log('no r');
      return (rslts[0].faq);
    }
  });
  console.log('top');
};
Bhuwan
  • 16,525
  • 5
  • 34
  • 57
Dori
  • 331
  • 1
  • 6
  • 18
  • possible duplicate of [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Leonid Beschastny Aug 12 '14 at 14:46
  • 2
    First, that's an asynchronous function so it won't return exactly when you want it. Second, you're returning from the callback, not from your main function. – Mike Cluck Aug 12 '14 at 14:48
  • A call (to `console.log`) is not a `return`. And [your callback is asynchronous](http://stackoverflow.com/q/23667086/1048572)! – Bergi Aug 12 '14 at 14:48

1 Answers1

2

The issue is that your call here is asynchronous. You need to pass in a callback and then call that callback with the return values.

Updated example:

exports.check_permitions = function (user_id, callback) {
    iapp.website_coll.find({}).where('admins_id').equals(user_id).exec(function(err, rslts) {
        if (err) {
            console.log(err);
            callback(err);
        }
        else if (rslts) {
            console.log(rslts[0].faq);
            callback(null, rslts[0].faq);
        }
        else if (!rslts) {
            console.log('no r');
            callback(null, null);
        }
    });
    console.log('top');
};

Here's a tutorial on the asynchronous concept in node: http://lostechies.com/johnteague/2012/11/30/node-js-must-know-concepts-asynchrounous/


EDIT: You have to pass in a callback.

Your calling code probably looks something like this:

var result = check_permitions(some_user_id);
// do something with result

You'll need to update it to this:

check_permitions(some_user_id, function(err, result) {
    // do something with result
})

I'd recommend learning more about asynchronous javascript code. It doesn't always execute top-down as you'd expect. The point of the callback is that it'll be called at some arbitrary point in the future, after the database results have returned, at which point the outer calling code has already finished execution.

furydevoid
  • 1,391
  • 8
  • 7