@marink0

Как прерывать цепочку промиса без выкидывания ошибки?

Как сделать, чтобы если срабатывал один return res.json(), то следующий уже не выполнялся? Не используя вкладывание.

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' })
то заголовки отправляются дважды и сервер ругается.
  • Вопрос задан
  • 167 просмотров
Решения вопроса 1
@levchak0910
answer.correct ? press({correct: true}) : next()
Async / await можна?
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);
}
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
summer Ярославль
от 100 000 до 140 000 ₽
КРАФТТЕК Санкт-Петербург
от 60 000 до 80 000 ₽
19 апр. 2024, в 20:43
20000 руб./за проект
19 апр. 2024, в 20:11
500 руб./за проект