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

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

我遇到了 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 函数一样工作?

更改您的代码以获取帖子,一旦您使用 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

        });

    });