[英]How to get more than one independent response data in Express js app.get callback
通過HTTP方法在Express應用程序中發送兩個獨立的MongoDB結果的最佳實踐是什么?
這是一個簡短的示例,它很清楚:
//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嗎?
還是應該以其他方式重新設計它?
謝謝!
您應該使用Promise來完成此任務:
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]});
});
});
當您致電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。
兩個數據庫查詢之間還將存在競爭條件,這意味着您不確定響應中數據的順序。
建議:
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.