在这里,我首先搜索机票,然后训练预订哪张票。 我是承诺的新手,所以我想知道这是正确的方法,还是可以在没有嵌套的情况下完成?
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)
})
});
答案 0 :(得分:0)
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)
});
});
答案 1 :(得分:0)
是的,您应该flatten it by return
ing the inner promise以便链接到它并且只需要一个错误处理程序。
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!
});
});