将多个Promise传入Node JS呈现
我想将来自3个不同promises的数据传递到nodej中的render函数中,以便与pug一起使用。将多个Promise传入Node JS呈现
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
问:我如何通过在渲染功能,这个数据。 ('图表',{info:statusChart,vuln:severityChart,count:countChart});
当我尝试这样我得到哈巴狗侧
VAR的结果= { “_75” 的结果如下:1, “_ 83”:0, “_ 18”:空, “_ 38”:{ “onRejected”:空, “承诺”:{ “_ 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”:空}}};
您将承诺传递给info,vuln和count变量。那些问题没有解决。为了得到这个工作,请执行下列操作
....
return Promise.all([statusChart, severityChart, countChart])
.then(([statusChartVal,severityChartVal,countChartVal]) => {
return res.render('graphs', {info: statusChartVal, vuln:
severityChartVal, count: countChartVal});
});
....
Promise.all解析何时只有所有的promise都解决了。所以,添加catch块。 –
新的承诺((解析,拒绝)=> {// 做些什么//
return new Promise((resolve, reject) => {
//Do Something //
Resolve(true);
});
Promise.all(Promise).then((responses) => {
resolve({
status: true,
data: data
});
});
}).then((response) => {
res.json(response);
});
使用'Promise.all'。 – Bergi
你真的应该编写一个带有id的助手函数,调用'new Promise'和'a.aggrate',并返回结果的承诺。 – Bergi