0
我使用express,mongoose和async。异步瀑布回调没有在猫鼬内部调用保存
在一个控制器上的更新方法,我打电话以下几点:
//note: we're within a constructor's prototype method, hence the 'self'. also body is simply the request body.
async.waterfall([
function(callback) {
self.collection.findById(body._id).exec(function(err, item) {
if(item) {
callback(null, item);
} else {
callback(err);
}
});
},
function(item, callback) {
//callback(null, item); //makes this task work, but not what I need
//merge two together models together, then save
item.save(_.extend(item, body), function(err, item) {
console.log('code here never seems to get called within the waterfall');
callback(null, item);
});
}
], function(err, results) {
console.log('hello', err, results);
self.res.json(results);
});
所以基本上我想要做的就是找到了ID文件,然后用合并的新对象我刚刚找到一个,保存它,并将结果作为JSON返回。但嵌套在.save中的回调函数似乎永远不会被调用。所以整个请求似乎挂起,并且瀑布中的最终功能永远不会被调用。
我可能是错的,但似乎save方法的回调被异步调用。我将如何去做这个工作?
注意:如果save方法的回调是异步的,那么为什么这似乎工作?
var _this = this;
var item = new this.collection(this.req.body);
item.save(function(err, data) {
_this.res.json(data);
});
该方法返回保存的对象为JSON就好了。
谢谢彼得。我感到很傻,我没有听清楚。 – ccnokes 2014-09-22 18:15:35
有人可以提供工作代码吗? – nottinhill 2015-10-06 14:31:00