Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda