繁体   English   中英

如何一次在node.js的函数内部编写两个操作?

[英]How to write two operations at a time inside function in node.js?

我的数据库中有两个表,我想使用nodejs使用一个函数获取两个数据

我的表名称是ContactGroup和Group

我的代码:

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

像上面的代码一样,我正在编写ContactGroup.findandcount和Group.findall,我通过邮递员检查了此api,但是只有一个在这里工作,我希望两个都在工作吗? 帮我!

您采用全局数组或对象并以下列方式使用它

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

将您的代码更改为此,然后尝试:

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

尽管其他答案是正确的,但正如我所见,有两个独立的异步函数,因此最好将它们并行填充(以提高性能),如下所示。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM