在结束AJAX请求之前等待node.jscallback完成

我正在使用前面的jQuery使用$ .post()进行AJAX发布请求。 我也传递一个成功的函数,它将返回的数据做一些事情。 在我的node.js服务器上,我使用express来处理请求,post请求调用另一个函数传递一个callback,在callback中执行res.send()。 我怎样才能得到请求不完成,直到callback完成?

我的客户端代码是:

$.post("/newgroup/", {name: newgroupname}, function(data) { console.log(data); // Returns undefined because requests ends before res.send }); 

我的服务器端代码是:

 app.post('/newgroup/', function(req, res){ insertDocument({name:req.body.name, photos:[]}, db.groups, function(doc){ res.send(doc); }); }); 

insertDocument函数是:

 function insertDocument(doc, targetCollection, callback) { var cursor = targetCollection.find( {}, {_id: 1}).sort({_id: -1}).limit(1); cursor.toArray(function(err, docs){ if (docs == false){ var seq = 1; } else { var seq = docs[0]._id + 1; } doc._id = seq; targetCollection.insert(doc); callback(doc); }); } 

如果您向我们显示的代码是真实的代码,那么唯一的可能性是您正在返回的doc实际上是undefined 。 在触发res.send()之前,客户端的callback不会触发。

你确定在insertDocument中的callback是否和你想象的一样? 通常callback是​​formsfunction(err,doc) ,即试试这个:

 app.post('/newgroup/', function(req, res){ insertDocument({name:req.body.name, photos:[]}, db.groups, function(err, doc){ res.send(doc); }); }); 

好吧,我find了答案,我不知道为什么这个工作,我只需要改变我发送到callbackvariables的名称,我认为这是因为它具有相同的名称作为参数,所以我改变了我的insertDocumentfunction看起来像这样

 function insertDocument(doc, targetCollection, callback) { var cursor = targetCollection.find( {}, {_id: 1}).sort({_id: -1}).limit(1); cursor.toArray(function(err, docs){ if (docs == false){ var seq = 1; } else { var seq = docs[0]._id + 1; } doc._id = seq; targetCollection.insert(doc); var new_document = doc; callback(new_document); }); } 

它可能是一个同步/asynchronous问题? 我不知道你用什么库来保存,但是这个电话应该是这样的吗?

 targetCollection.insert(doc, function(err, saveddoc) { if (err) console.log(err); callback(saveddoc); });