[英]Constructing json response. NodeJS send empty response
我有此代码,我想在其中发送包含通过多次请求数据库获得的数据的响应。 我不明白为什么它会发送空响应。
var express = require('express'),
router = express.Router(),
database = require('../database');
router.get('/', function(req, res, next){
res.writeHead(200, {"Content-Type": "application/json"});
var ttt;
var yyy;
database.getTagType().then(function(data) {
ttt = "pfff";
});
database.getSpecie().then(function(data) {
yyy = "akkhhh";
});
var json = JSON.stringify({
anObject: ttt,
anArray: yyy,
});
res.end(json);
});
module.exports = router;
问题是Promise.then
异步性质。 您会看到,在两个诺言都将被解决之前,将调用JSON.stringify
和res.end
。 若要仅在获取所有数据时发送响应,则必须使用Promise.all
方法。
这是一个如何完成的示例:
router.get('/', function(req, res, next){
var promises = [];
promises.push(database.getTagType().then(function(data){
return "pfff";
}));
promises.push(database.getSpecie().then(function(data) {
return "akkhhh";
}));
Promise.all(promises).then(function(values) {
// Actually, express can stringify response for us. Also it adds
// correct "Content-Type" header.
res.json({
anObject: values[0],
anArray: values[1]
});
}).catch(function(error) {
// Something went wrong. Let the error middleware deal with the problem.
next(error);
// Instead we can just send an error response, like so:
// res.status(500).json({error: error.toString()});
});
});
数据库调用是异步的。 它们正在返回promise,并且您要追加then
函数,但是javascript运行的方式是,该函数调用getTagType
和getSpecie
,然后在promise解决且db调用结束之前发送带有res.end()
的响应。
您需要确保等待所有promise解析后再回复响应,这本质上要求嵌套then()
函数。
像这样:
router.get('/', function(req, res, next){
res.writeHead(200, {"Content-Type": "application/json"});
var tag = database.getTagType();
// `tag` is now a promise
var specie = database.getSpecie();
// `specie` is a promise
Promise.all([tag, specie]).then(function(values) {
// this code is executed once both promises have resolved, the response has come back from the database
var json = JSON.stringify({
tag: values[0],
specie: values[1]
)};
res.end(json);
});
});
此函数将立即返回,但在数据库调用完成之前不会调用res.end()
。
一旦将async/await
添加到语言中,此代码将变得更干净:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.