2

I'm trying to write my own wrapper for the mongojs collection.find method that should return the collection items selected by the specified query (querying isn't implemented yet, it should simply select all results). The problem is that I'm not getting back an array of results. It seems like the find method does some kind of async callback. So how can I force a synchronous call or force my script to wait?

Collection.prototype.find = function () {
    var result = new Array;
    if (Bridge.isServer) {
        db.collection(name).find(function(err, items) {
            items.forEach(function(item) {
                result.push(item);
            });
        });
    }
    return result;
}
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
Pascal Bayer
  • 2,615
  • 8
  • 33
  • 51
  • 2
    Not the answer you want, but the right answer is here: http://stackoverflow.com/questions/3919075/javascript-design-patterns-dealing-with-unwanted-asynchrony?rq=1 – mjhm Jan 07 '13 at 17:07
  • Thanks, but adding another callback is not what I want, I want to force my function to wait until the results are coming back from the database and then return them. I know that this will block my system for the time I've to wait. – Pascal Bayer Jan 07 '13 at 17:14
  • 1
    Node.js is asynchronous and any possible blocking is huge anti-patern and will be prevented by any force. There is nothing you can't do with async callbacks, so please use them as they actually make node.js fast. – moka Aug 30 '13 at 12:00

1 Answers1

0

I think you should consider making your functions asynchronous, but if you insist on writing synchronous functions, there is a github project for making async functions synchronous.

Here's another SO post dealing with the same topic: Convert an asynchronous function to a synchronous function

Community
  • 1
  • 1
Josh C.
  • 4,303
  • 5
  • 30
  • 51