[英]node.js - post response is not waiting for callback to complete
我正在使用node.js http服务器。 服务器已连接到mongodb。 我正在向服务器请求发布请求,以从mongodb获取文档。 但是发布响应并不等待mongodb回调完成。 因此,我没有在客户端获得所需的输出。 如何处理呢?
http.createServer(function(request, response) {
if(request.method == "POST") {
var body = '';
request.on('data', function(chunk) {
console.log(chunk.toString());
body += chunk;
});
request.on('end', function() {
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) {
console.log("We are not connected");
}
else {
var sysInfo = db.collection('sysInfo');
var jsonObj = sysInfo.find().toArray();
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(jsonObj);
}
});
})
}
});
toArray
是异步的,因此它通过回调提供结果,而不是返回结果。
因此,该部分应为:
sysInfo.find().toArray(function(err, docs) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end(docs);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.