I'm making a post request and it requires several things to happen. It's native JavaScript promise not any library. Initially used nested promise and it was working but code was not that good. So, I decided to go with Promise chain and I'm stuck. The post route always returns {success:false, err:{}}, which it should when something goes wrong. But the err object is empty object. Why is that? After some tests I found the problem is in the second then where I'm returning AvaiablexForX.findOne({isX:false});. Don't worry about variables names, for the sake idea I have changed the actual names.
router.post("/delevery_request",
passport.authenticate("jwt", {session:false}),
(req, res) => {
const requestInputFields = {};
const foundxProfile = {};
const xProfileId = "";
const newxRequestId = "";
requestInputFields.isAccepted = false;
XProfile.findOne({user:req.user.id})
.then(xProfile => {
foundxProfile= xProfile;
requestInputFields.xId = xProfile._id;
return AvaiablexForX.findOne({isX:false});
})
.then( avaiablexForX =>
{
// this does not reach here
console.log("available x for X", avaiablexForX);
requestInputFields.xToBeDonateId = avaiablexForX._id;
xProfileId = avaiablexForX.xProfileId;
return requestInputFields;
})
.then( result => new RequestxY(result).save()).
then( requestForxY => {
foundxProfile.requestedxDeleivery.unshift(requestForxY._id);
return foundxProfile.save();
}).
then( xProfile => res.json({success:true}))
.catch(err => {
// output in body of request: {success:false, err:{}}
res.status(404).json({success:false, err:err})
}
);
});