如何使用asyn重构nodejs代码并避免回调地狱

时间:2017-01-31 12:54:45

标签: javascript node.js mongodb express

我对节点相对较新,我正在尝试了解如何异步或承诺或任何使我的代码更好的东西。 这是我的代码的一个例子

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

我读到了异步和承诺,申请代码的最佳方式是什么?

1 个答案:

答案 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"});
  });
});