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