我是 Nodejs 新手,所以我有一个基本问题,这是我的 scanrio
- 我有一个 JavaScript 客户端,它向 Node 服务器发出 http 请求以从数据库读取值。
一旦 Node 服务器收到请求,它就会进行一个简单的数据库调用,并在响应中将数据返回给客户端,这就是问题所在。
router.get('/state', function(req, res){ var result = dbServer.makeDBCall();//Before this line executes and returns the result the next line executes res.send(result); }
来自 Node 服务器的数据库调用是异步的,因此在返回结果之前, Node 服务器已经向客户端发送了空白响应。实现这一目标的标准/可接受的方法是什么,我知道我可以使用异步阻塞 Node 线程,但是 Node 的整个目的就消失了?
最佳答案
这取决于您使用哪种数据库 Node 模块。
除了标准的回调方式之外,还有promise方式。 pg-promise图书馆就是其中之一。
查看示例代码:
this.databaseConnection.makeDBCall('your query...')
.then(function(dbResponse) {
// Parse the response to the format you want then...
res.send(result);
})
.catch(function(error) {
// Handle error
res.send(error.message);
});
@spdev:我看到您的评论之一,您担心 Node 如何真正知道向谁回复响应,尤其是当有多个请求时。
这是一个非常好的问题,老实说 - 我对此也不太了解。
简而言之,答案是是,Node 在 HTTP 请求通过时通过创建相应的 ServerResponse 对象以某种方式处理此问题。这个对象似乎有一些智能,可以告诉 Nodejs 网络堆栈在解析为数据包时如何将自身路由回调用者。
我尝试在谷歌上搜索一下答案,但没有找到太多答案。我希望 ServerResponseObject 文档能为您提供更多见解。如果您得到答案请与我分享,谢谢!
https://nodejs.org/api/all.html#http_class_http_serverresponse
关于node.js - Node 异步调用返回数据作为响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38137397/