简体   繁体   English

如何在Express js app.get回调中获取多个独立响应数据

[英]How to get more than one independent response data in Express js app.get callback

What is the best practice to send two independed MongoDB results in Express application via HTTP Method? 通过HTTP方法在Express应用程序中发送两个独立的MongoDB结果的最佳实践是什么?

Here is a short example which makes it clear: 这是一个简短的示例,它很清楚:

//app.js
var express = require('express');
var app = express();
var testController = require('./controllers/test');
app.get('/test', testController.getCounts);
...

Following getCounts() function wouldn't work because I can't send the response twice. 跟随getCounts()函数将不起作用,因为我无法两次发送响应。

///controllers/test
exports.getCounts = function(req,res) {
   Object1.count({},function(err,count){
    res.send({count:count});
   });
   Object2.count({},function(err,count){
    res.send({count:count});
   });
};

Anyway, I would like to have those two counts in one response object. 无论如何,我想在一个响应对象中包含这两个计数。

Should I call Object2.count in the callback of Object1 even if they are not dependent to each other? 即使它们彼此不依赖,也应该在Object1的回调中调用Object2.count吗?

Or should I re-design it somehow else? 还是应该以其他方式重新设计它?

Thank you! 谢谢!

You should use Promise to achieve this task : 您应该使用Promise来完成此任务:

 function getCount(obj) {
    return new Promise(function (resolve, reject) {
        obj.count({}, function(err,count) {
             if(err) reject();
             else resolve(count);
        });
    });
 }

With Promise.all you can trigger the two request and retrieve the results in order to add it to the response 使用Promise.all您可以触发两个请求并检索结果,以将其添加到响应中

 exports.getCounts = function(req,res) {
    Promise.all([getCount(Object1), getCount(Object2)])
    .then(function success(result) {
        res.send({'count1':result[0], 'count2':result[1]});
    });
 });

When you call res.send you will end the response for the request. 当您致电res.send您将结束请求的响应。 You could instead use res.write , which will send a chunk to the client, and when done call res.end ; 您可以改用res.write ,它将向客户端发送一个块,完成后调用res.end

Example: 例:

app.get('/endpoint', function(req, res) {
   res.write('Hello');
   res.write('World');
   res.end();
});

However, it seems like you are trying to send json back to the client which raises and problem: writing to object separately will not be valid json. 但是,似乎您正在尝试将json发送回客户端,这引发了问题:单独写入对象将不是有效的json。

Example: 例:

app.get('/endpoint', function(req, res) {
   res.write({foo:'bar'});
   res.write({hello:'world'});
   res.end();
});

The response body will now be: {foo:'bar'}{hello:'world'} which is not valid json. 响应正文现在将是: {foo:'bar'}{hello:'world'} ,它是无效的json。

There will also be a race condition between the two db queries, which means that you are not certain about the order of the data in the response. 两个数据库查询之间还将存在竞争条件,这意味着您不确定响应中数据的顺序。

Suggestion: 建议:

exports.getCounts = function(req,res) {
  var output = {};      

  Object1.count({},function(err,count){
     output.count1 = count;

     Object2.count({},function(err,count){
       output.count2 = count;
       res.send(output);
     });
  });
};

//Response body
{
   count1: [value],
   count2: [value]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM