M
M
marink02018-04-07 18:35:55
JavaScript
marink0, 2018-04-07 18:35:55

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

Now if it works
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

1 answer(s)
L
levchak0910, 2018-04-07
@marink0

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 question

Ask a Question

731 491 924 answers to any question