nodejs表达响应追加到列表中 [英] nodejs express response append into a list
问题描述
我在一条路由中有多个res.send
,如何将它们全部附加到一个中并在末尾发送累积的列表?
我更喜欢以以下形式进行操作:
I have multiple res.send
in one route, how can I append them all into one and send the accumulated list at the end?
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.
因此最好选择一个您选择的库(例如 async ),然后执行异步过程,然后在回调中发送结果.
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.parallel([
function(callback) { ... },
function(callback) { ... }
], function(err, results) {
// send your result here
});
请注意,如果您使用的是.parallel
,则在其中一个诺言失败的情况下,将立即调用最终回调.参见 docu
Note that if you are using .parallel
the final callback will be immediatly called if one of the promises fails. see the docu
这篇关于nodejs表达响应追加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!