我正在开发 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);
});
关于javascript - node.js - 发布响应不等待回调完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28213019/