0

i found some plugin of mongodb for nodejs ,but it seems alway use callback function to return search result, i just wanna to get the result in return by straight

I can't get the correct return by use this code:

index.prototype.a = function(){
    var vars = {};
    vars.something1 = {};
    vars.something2 = 123;
    mongous("db.test").find({name:'shura'},function(r){
        if(r){
            vars.something3= true;
        }else{
            vars.something3= false;
        }
    });
    return vars; 
}

This code is what I want:

index.prototype.a = function(){
    var vars = {};
    vars.something1 = {};
    vars.something2 = 123;
    var result = mongo_plugin("db.test").search({name:'shura'});
    vars.something3 = result?true:false;
    return vars; 
}

how can i make the vars.something3 exist in return?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Shura
  • 25
  • 1
  • 7
  • probably you want to do this synchronous way! – Sunny Sharma Mar 30 '14 at 08:02
  • possible duplicate of [What is the right way to make a synchronous MongoDB query in Node.js?](http://stackoverflow.com/questions/12030248/what-is-the-right-way-to-make-a-synchronous-mongodb-query-in-node-js) – Sunny Sharma Mar 30 '14 at 08:03
  • I would seriously urge you to just do a callback. Anything that does this synchronously is going to be hacking away at node.js and making things generally scarier (and tearing down one of the strongest selling points of node.js). If you just don't like the christmas tree look of callback code, consider the [async library](https://github.com/caolan/async) – Tim Brown Mar 30 '14 at 08:22

1 Answers1

0

The selling point of node.js is the asynchronous nature of it. You should either roll with the awesome or use a scripting language like Ruby or Python. Here is the node-ish way to do what you wanted (or how I learned to stop worrying and love the callback):

index.prototype.a = function(cb){
    var vars = {};
    vars.something1 = {};
    vars.something2 = 123;
    mongous("db.test").find({name:'shura'}, function(err, r){
        if(err) { return cb(err) };
        vars.something3 = r ? true : false;
        cb(null, vars);
    });
}
Tim Brown
  • 3,173
  • 1
  • 18
  • 15
  • First all to thank you for your help me. Maybe your way is right, but the result is not what I want – Shura Mar 31 '14 at 05:22
  • Yeah, the asynchronous nature of node is a bit weird at first, but makes sense once you get into it. There are libraries out there to help manage the async flow so it doesn't look as goofy. [async](https://github.com/caolan/async) - I like this guy as it's pretty small and makes things less christmas tree. [iced coffeescript](http://maxtaco.github.io/coffee-script/) - This one has more magic, but makes the code LOOK properly synchronous, but it has a different syntax from normal js code. – Tim Brown Apr 01 '14 at 01:08