Search code examples
javascriptnode.jsexpressnode-orm2

Is there a way to call the each function in synchronous way in node-orm?


I'm having a problem with node-orm2's asynchronous behavior. I have a query like this:

req.models.posts
   .find(...)
   .order('-whatever')
   .each(doMagic) //Problem happens here
   .filter(function(post) { ... })
   .get(callback);

function doMagic(post, i) {

    post.getMagic(function(err, magic) {
        ...
    });     
};

My problem is that, since what happens inside post.getMagic() is asynchronous, my callback function gets executed before doMagic finishes. Checking the source code I verified this is the normal behavior, but since this is an express app, my server responds with the wrong information.

I tried using waitfor to make the call to getMagic synchronous, with no success. This is probably something I'm missing. Is there a way to make the each function work like a synchronous map function?


Solution

  • Change your code to get posts and once you have them iterate over them using async.js and once done send response.

    Something like:

    var async = require('async');
    
    req.models.posts
        .find(...)
        .order('-whatever')
        .each()
        .filter(function(post) {...
        })
        .get(function(posts) {
    
            //iterate over posts here
            async.eachSeries(posts, function(file, callback) {
                post.getMagic(function(err, magic) {
    
                    //here comes the magic
    
                    //and then callback to get next magic
                    callback();
    
                });
            }, function(err) {
    
                //respond here
    
            });
    
        });