简体   繁体   English

nodejs表达响应追加到列表中

[英]nodejs express response append into a list

I have multiple res.send in one route, how can I append them all into one and send the accumulated list at the end? 我在一条路由中有多个res.send ,如何将它们全部附加到一个并在末尾发送累积的列表? I prefer to do it in the following form: 我更喜欢以以下形式进行:

{
"writer": {success message},
"archive": {success message},
 ...
}

and another one like above for the list errors. 另一个类似上面的错误列表。 here is the code: 这是代码:

router.post('/some/route', function (req, res) {
    if (req.isLoggedIn()) {
        return res.status(403).json({});
    }
    MyModel.findById(req.user._id,function (err, data) {
        if(err || data.rights !== 'super'){
            return res.status(403).json({});
        }
        if(req.body.writer){
            Books.update(
                { writer : req.body.id},
                { $set : { writer : req.body.writer} },
                function (err) {
                    if(err){
                        res.status(500).send(err);
                    }
                    else{
                        res.status(200).send('updated successfully.');
                    }
                }
            );
        }else{
            Books.remove({writer: req.body.id}, function(err){
                if (err){ return console.log(err)}
            });
        }

        MetaInfo.findOneAndRemove({_id: req.body.id}, function (err, data) {
            console.log(err);            
        });
        Archive.findOne({_id: req.body.id},function (err, data) {

            smtpTransporter.sendMail({...}, function (error, response) {
                if (error) {
                    console.log(error);
                } else {
                    console.log("Mail sent");
                }
                smtpTransporter.close();
            });

            data.remove();
            if (err) {
                console.log(err);
                return res.status(200).json({
                    success: false,
                    message: 'server error',
                    err: err
                });
            }
            res.status(200).json({
                success: true
            });
        })
    });
});

I assume your problem are the asynchronous calls to the database. 我假设您的问题是对数据库的异步调用。

So best take a library of your choice (for example async ) and do your async processes, in the callback then finally send your result. 因此,最好采用您选择的库(例如async )并进行异步处理,然后在回调中最后发送结果。

Your result could look like this: 您的结果可能如下所示:

 async.parallel([ function(callback) { ... }, function(callback) { ... } ], function(err, results) { // send your result here }); 

Note that if you are using .parallel the final callback will be immediatly called if one of the promises fails. 请注意,如果您使用.parallel ,则其中一个promise失败时,将立即调用最终回调。 see the docu 纪录片

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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