简体   繁体   中英

How to refactor nodejs code using asyn and avoiding callback hell

I am relatively new to node, and am trying to learn about the how to async or promises or anything to make my code better. here's an example of my code

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

I read about async and promises, what is the best way to apply to my code?

I would personally go for Promises. It could look like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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