有没有办法在node-orm中以同步方式调用每个函数?

时间:2015-05-05 12:26:52

标签: javascript node.js express node-orm2

我遇到了node-orm2异步行为的问题。我有这样的查询:

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) {
        ...
    });     
};

我的问题是,由于post.getMagic()内部发生的事情是异步的,我的回调函数会在doMagic完成之前执行。检查source code我验证了这是正常行为,但由于这是一个快速应用程序,我的服务器响应错误的信息。

我尝试使用waitfor来同步调用getMagic,但没有成功。这可能是我想念的东西。有没有办法让each函数像同步map函数一样工作?

1 个答案:

答案 0 :(得分:1)

更改您的代码以获取帖子,一旦您让它们使用async.js迭代它们并完成发送响应。

类似的东西:

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

        });

    });