我想将3个不同的promises中的数据传递给nodejs中的render函数,以便与pug一起使用。
var promise = require('promise');
var statusChart = new promise(function (resolve, reject) {
a.aggregate(
[
{
$group: {
_id: '$status',
count: {$sum: 1}
}
}
], function (err, status) {
if (err) {
console.log(err);
reject(err);
} else {
resolve(status);
}
});
});
var severityChart = new promise(function (resolve, reject) {
a.aggregate(
[
{
$group: {
_id: '$severity',
count: {$sum: 1}
}
}
], function (err, vuln) {
if (err) {
console.log(err);
reject(err);
} else {
resolve(vuln);
}
});
})
var countChart = new promise(function (resolve, reject) {
a.count(function (err, count) {
if (err) {
console.log(err);
reject(err);
} else {
resolve(count);
}
});
})
statusChart.then((message) => {
console.log(message);
});
severityChart.then((data) => {
console.log(data);
});
countChart.then((item) => {
console.log(item);
});
上面的代码工作正常,将返回我的结果
[ { _id: 'Medium', count: 6 },
{ _id: 'High', count: 15 },
{ _id: 'Low', count: 1 } ]
[ { _id: 'New', count: 1 },
{ _id: 'Closed', count: 1 },
{ _id: 'In Progress', count: 11 },
{ _id: 'Pending', count: 9 } ]
22
问题:如何在渲染功能中传递此数据。
res.render('graphs',{info:statusChart,vuln:severityChart,count:countChart});
当我以这种方式尝试时,我会在哈巴狗那边得到以下结果
var results = {“_ 75”:1,“_ 83”:0,“_ 18”:null,“_ 38”:{“onRejected”:null,“promise”:{“_ 75”:0,“_ 83” :0, “_ 18”:空, “_ 38”:空}}}; var status = {“_ 75”:1,“_ 83”:0,“_ 18”:null,“_ 38”:{“onRejected”:null,“promise”:{“_ 75”:0,“_ 83”:0, “_18”:空, “_ 38”:空}}}; var total = {“_ 75”:1,“_ 83”:0,“_ 18”:null,“_ 38”:{“onRejected”:null,“promise”:{“_ 75”:0,“_ 83”:0, “_18”:空, “_ 38”:空}}};
答案 0 :(得分:0)
您正在将promises传递给info,vuln和count变量。那时候还没有解决。要使其正常工作,请执行以下操作
....
return Promise.all([statusChart, severityChart, countChart])
.then(([statusChartVal,severityChartVal,countChartVal]) => {
return res.render('graphs', {info: statusChartVal, vuln:
severityChartVal, count: countChartVal});
});
....
答案 1 :(得分:0)
新承诺((解决,拒绝)=> { //做点什么//
return new Promise((resolve, reject) => {
//Do Something //
Resolve(true);
});
Promise.all(Promise).then((responses) => {
resolve({
status: true,
data: data
});
});
}).then((response) => {
res.json(response);
});