【发布时间】:2018-11-28 21:56:14
【问题描述】:
我有一个正在等待 HTTPREQUESTS 的 NODEJS 服务器。根据请求,它从 MongoDB 获取一些数据并将其作为响应发送回。 JavaScript 是一种同步语言,因此响应总是在从数据库获取数据之前发送。这是我去 localhost:8080 时编写的测试代码,如果我刷新我得到实体,我什么也得不到。就像我说的我知道为什么,我的问题是我不知道如何让服务器等待响应,直到数据库回答。我需要一个事件或其他东西,但我不知道我应该如何实现它......
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
var requrl= "localhost:2442"
var testResult = "";
http.createServer(function(requrl,res){
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, { useNewUrlParser: true },function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("UserInformations").find({name:"a"},{projection: {_id:0}}).toArray(function(errorinfind,result){
if(errorinfind)throw errorinfind;
db.close();
testResult = result[0].name;
});
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(testResult.toString());
res.end();
}).listen(8080);
【问题讨论】:
-
您需要在数据库查询的回调中执行 response.write