2016-08-18 24 views
0

通过HTTP方法在Express应用程序中发送两个独立的MongoDB结果的最佳做法是什么?如何在Express js app.get回调中获取多个独立响应数据

下面是一个简单的例子,这使得它明确:

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

继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}); 
    }); 
}; 

无论如何,我想在一个响应对象中有这两个计数。

我应该在Object1的回调中调用Object2.count,即使它们不相互依赖吗?

或者我应该重新设计它吗?

谢谢!

回答

1

你应该用承诺来实现这一任务:

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

随着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]}); 
    }); 
}); 
+0

在功能getCount将 - 你可能想打电话,而不是 'obj.getCount' obj.count“。 我刚刚尝试过,回应是{“count1”:[27,1]}。所以不完全如预期。 – sachad

+0

@sachad对不起,我犯了一个错误,我编辑了我的帖子,它现在应该工作 –

+0

谢谢!像这个解决方案。 – sachad

0

当您打电话res.send您将结束请求的响应。您可以改为使用res.write,它会向客户端发送一个块,完成后请致电res.end;

例子:

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

但是,好像你要发送的JSON回这提高和问题的客户端:编写单独的对象将是无效的JSON。

实施例:

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

响应身体现在将是:{foo:'bar'}{hello:'world'},其不是有效的JSON。

这两个db查询之间也会有竞争状态,这意味着您对响应中的数据顺序不确定。

建议:

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] 
} 
相关问题