2

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?

William Barbosa
  • 4,936
  • 2
  • 19
  • 37
  • Did you try callback in doMagic()? function doMagic(post, i, callback)... and call it after post.get...... – Molda May 05 '15 at 14:53
  • The doMagic function gets called once for each element retrieved from the database, so this won't work – William Barbosa May 05 '15 at 14:57
  • Then change your code to get posts and once you have them iterate over them using async.js and once done send response – Molda May 05 '15 at 15:33
  • Thanks a lot, @Molda, you saved the day :D If you want the rep, answer this question and I'll gladly accept it – William Barbosa May 14 '15 at 11:57

1 Answers1

1

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

        });

    });
Molda
  • 5,619
  • 2
  • 23
  • 39