Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

204
Visualizações
Mongoose promises and node, return response earlier

I am working on a MERN stack project. I saw that some functions in server side related to fetching or saving data in mongodb have lot of callbacks. In order to avoid callbacks hell, now I am trying promises based solution. However I have encountered issue with this promised based solution. I have a condition and depending on its value I want to either proceed further or just return response and stop.

  const mId = req.body.mId;
  const cId = req.body.cId;
  const lId = req.body.lId;
  LP.findOne({
    'userId': lId,
    'courseId': cId
  })
  .then( lP => {
      return lP.materials;
  })
  .then( materials => {
    if( materials.includes(mId) ) {
      console.log('A')
      return res.json({'status': 'success'})
    }
    else {
      materials.push(materialId)
      return LP.findOneAndUpdate({
        'userId': learnerId,
        'courseId': courseId
      }, {
        $set: { materials: materials}
      }, {
        new: true
      })
    }
  })
  .then( update => {
    console.log('B')
    return res.json({ 'status': 'success' })
  })
  .catch( err => {
    return res.json({ 'status': 'fail' })
  })

In above code after A is printed B is also printed and further code is executed which gives me: Cannot set headers after they are sent to the client error. I think that is how promises are supposed to work. But what are the possible solution to avoid this problem. How to return res early on and do not execute code further.

Thanks

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Just dont return to stop the chain:

  const mId = req.body.mId;
  const cId = req.body.cId;
  const lId = req.body.lId;
  LP.findOne({
    'userId': lId,
    'courseId': cId
  })
  .then( lP => {
      return lP.materials;
  })
  .then( materials => {
    if( materials.includes(mId) ) {
      console.log('A')
      res.json({'status': 'success'})
    }
    else {
      materials.push(materialId)
      return LP.findOneAndUpdate({
        'userId': learnerId,
        'courseId': courseId
      }, {
        $set: { materials: materials}
      }, {
        new: true
      })
    }
  })
  .then( update => {
    console.log('B')
    res.json({ 'status': 'success' })
  })
  .catch( err => {
    res.json({ 'status': 'fail' })
  })
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda