Answer the question
In order to leave comments, you need to log in
How to break a promise chain without throwing an error?
How to make it so that if one worked return res.json()
, then the next one was no longer executed? Not using nesting.
newArticle
.save()
.then(article => {
Section
.findOneAndUpdate({ _id: article.section }, {$push: {"articles": article._id}}, {new: true})
.then(section => {
if (section === null) return res.json({ message: 'No sections found' })
})
.catch((err) => {
return next(err)
})
return article
})
.then(article => {
return res.status(201).json({
status: 'OK',
article
})
})
.catch(err => {
return next(err)
})
if (section === null) return res.json({ message: 'No sections found' })
then the headers are sent twice and the server swears.
Answer the question
In order to leave comments, you need to log in
Async / await is possible?
async (req, res) => {
...
try {
let article = await newArticle.save();
let section = await Section.findOneAndUpdate({ _id: article.section }, {$push: {"articles": article._id}}, {new: true});
if (section === null) return res.json({ message: 'No sections found' });
res.status(201).json({
status: 'OK',
article
});
}
catch(e) {
console.log(e);
next(e);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question