[英]How to write two operations at a time inside function in node.js?
I have two tables in my database, i want to get both datas with one function using nodejs 我的数据库中有两个表,我想使用nodejs使用一个函数获取两个数据
My table name is ContactGroup and Group 我的表名称是ContactGroup和Group
My code: 我的代码:
exports.getNewGroup = function (req, res) {
ContactGroup.findAndCountAll({
attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
'contactCount'
]],
include: [{
model: Group,
}],
}).then(seenData => {
console.log('seenData:', seenData);
});
Group.findAll().then(function (data) {
return res.status(200).send(data);
}).catch(function (err) {
return res.status(400).send(err.message);
});
};
Like above code, i am writing ContactGroup.findandcount and Group.findall, i checked this api via postman, but only one working here, I want both of them working? 像上面的代码一样,我正在编写ContactGroup.findandcount和Group.findall,我通过邮递员检查了此api,但是只有一个在这里工作,我希望两个都在工作吗? help me! 帮我!
you take a global array or object and use it in follwing manner 您采用全局数组或对象并以下列方式使用它
exports.getNewGroup = function (req, res) {
var globalObj={};
ContactGroup.findAndCountAll({
attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
'contactCount'
]],
include: [{
model: Group,
}],
}).then(seenData => { globalObj.seendata=seenData;return Group.findAll();})
.then(function (data) {
globalObj.alldata=data;
return res.status(200).send(globalObj);
}).catch(function (err) {
return res.status(400).send(err.message);
});
};
Change your code to this and try : 将您的代码更改为此,然后尝试:
exports.getNewGroup = function (req, res) {
ContactGroup.findAndCountAll({
attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
'contactCount'
]],
include: [{
model: Group,
}],
}).then(seenData => {
console.log('seenData:', seenData);
Group.findAll().then(function (data) {
return res.status(200).send(data);
}).catch(function (err) {
return res.status(400).send(err.message);
});
});
};
although others answers are correct but as i saw there are two independent async function so it's better to populate them parallel (more performance gain) as below. 尽管其他答案是正确的,但正如我所见,有两个独立的异步函数,因此最好将它们并行填充(以提高性能),如下所示。
exports.getNewGroup = function (req, res) {
p1= ContactGroup.findAndCountAll({
attributes: ['id', [sequelize.fn('COUNT', sequelize.col('group.id')),
'contactCount'
]],
include: [{
model: Group,
}],
})
p2 =Group.findAll()
Promise.all([p1,p2]).then(values => {
console.log(values);
})
.catch(function (err) {
return res.status(400).send(err.message);
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.