0

Here I am first searching for ticket and then train for which ticket is booked. I am new to promises so I want to know this is the right way or it can be done without nesting?

router.get('/ticket/:id', isLoggedIn, (req, res) => {
    Ticket.findById(req.params.id)
    .populate('passengers')
    .exec()
    .then(foundTicket => {
        Train.findById(foundTicket.trainDetails._id)
        .exec()
        .then(foundTrain => {
            res.render("ticket",{ticket:foundTicket, train:foundTrain});
        })
        .catch(err => {
            console.log(err)
        })
    })
    .catch(err => {
        console.log(err)
    })
});
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • I don't really see how else you'd do it, other than storing the error callback in a variable, and using that: `const err = e => console.log(e); /**/ .catch(err);` – Cerbrus Jan 03 '18 at 11:33

2 Answers2

0

Yo can flatten it even further by returning the 2nd promise. Catch will catch any error in the chain.

router.get('/ticket/:id', isLoggedIn, (req, res) => {
    Ticket.findById(req.params.id)
    .populate('passengers')
    .exec()
    .then(foundTicket => {
        return Train.findById(foundTicket.trainDetails._id)
        .exec();
    }).then(foundTrain => {
            res.render("ticket",{ticket:foundTicket, train:foundTrain});
    }).catch(err => {
        console.log(err)
    });
});
Abhyudit Jain
  • 3,640
  • 2
  • 24
  • 32
0

Yes, you should flatten it by returning the inner promise so that you can chain onto it and need only a single error handler.

router.get('/ticket/:id', isLoggedIn, (req, res) => {
    Ticket.findById(req.params.id).populate('passengers').exec()
    .then(foundTicket =>
        Train.findById(foundTicket.trainDetails._id).exec()
    ).then(foundTrain => {
        res.render("ticket",{ticket:foundTicket, train:foundTrain});
    }, err => {
        console.log(err);
        res.status(500); // don't forget to respond!
    });
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375