我对节点相对较新,我正在尝试了解如何异步或承诺或任何使我的代码更好的东西。 这是我的代码的一个例子
router.post('/delete', function (req, res) {
var bus_id = req.body.selected[0];
Bus.remove({_id: bus_id}, function (err) {
if (err) {
res.json({status: "error", message: "please enter a valid bus_id"});
} else {
User.remove({refid:bus_id},function(err){
if (err) {
res.json({status: "error", message: "bus user wasn't deleted"});
return;
} else {
res.json({status: "success",message: "bus and bus user were deleted"});
}
});
}
});
});
我读到了异步和承诺,申请代码的最佳方式是什么?
答案 0 :(得分:3)
我个人会去寻求承诺。它可能看起来像这样。
router.post('/delete', function (req, res) {
var bus_id = req.body.selected[0];
Bus.remove({_id: bus_id}).exec().then(function(bussRemoved) {
return User.remove({refid: bus_id}).exec();
}).then(function(userRemoved) {
res.json({status: "success",message: "bus and bus user were deleted"});
}).catch(function (err) {
res.json({status: "error", message: "please enter a valid bus_id"});
});
});