有没有办法在node-orm中同步调用每个函数?
我遇到了node-orm2asynchronous行为的问题。 我有这样的查询:
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()
里面发生的事情是asynchronous的,我的callback函数在doMagic
完成之前执行。 检查源代码我validation了这是正常的行为,但由于这是一个快速的应用程序,我的服务器响应错误的信息。
我尝试使用waitfor来调用getMagic
同步,没有成功。 这可能是我错过的东西。 有没有办法使each
function像一个同步map
function工作?
改变你的代码来获取post,一旦你有他们迭代使用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 }); });