Currently when coupon code is invalid I am getting response as invalid code with 400, invalidInput. But it also throwing log as: "crash Cannot set headers after they are sent to the client"
After debugging I realized my return is not exiting the chain and its going to next block of chain.
Why return statement does not exit the entire chain here?
Is it correct implementation of promise chaining with exit strategy?
MasterOrder.findOne({
where: {
fk_user_id: uid,
id: orderId,
status: 0,
}
}).then(function(orderObj) {
if (!orderObj) {
return res.fail("Invalid Order ID", 400, "invalidInput");
}
return HUSListing.findByPk(orderObj.fk_listing_id);
}).then(function(listingDetails) {
if (!listingDetails) {
return res.fail("Invalid Order ID With Listing", 400, "invalidInput");
}
return isValidBooking({at: req.body.time, listingId: req.body.listing_id});
}).then(function(isValidBookingResult) {
if (!isValidBookingResult) {
return res.fail("The requested not available", 400, "invalidInput");
}
return db.sequelize.query(
`SELECT user.firstName, user.lastName,
FROM HUSListing`);
}).then(function(HUSResultData) {
if (HUSResultData.length == 0) {
return res.fail("Listing not found", 400, "invalidInput");
}
let couponCodeObj = {
couponCode: couponCode,
uid: uid
}
return validateCoupon(couponCodeObj);
}).then(function(couponData) {
if (!couponData.isApplicable) {
return res.fail(couponData.message, 400, "invalidInput");
}
console.log("COMMING HERE");
couponID = couponData.data.id;
return upsertUserCoupon({
fk_user_id: uid,
fk_coupon_id: couponData.id,
isUsed: 1,
fk_masterOrder_id: orderId
}, {
fk_masterOrder_id: orderId,
});
}).then(function(r) {
if (!r || !r.id) {
console.log("COMMING HERE 1");
return res.fail("FAILED TO upsertUserCoupon", 500, "internalServerError");
}
return upsertMasterOrder({
taxAmount: taxAmount,
payableAmount: payableAmount,
payableAmountInCent: payableAmount * 100,
fk_coupon_id: couponID,
discountedPrice: discountedPrice,
}, {
id: orderId
});
}).then(function(upsertMasterOrderResult) {
if (upsertMasterOrderResult && upsertMasterOrderResult.id > 0) {
console.log("COMMING HERE 2");
return res.respondCreated(upsertMasterOrderResult);
} else {
console.log("COMMING HERE 3");
return res.fail("FAILED TO APPLY COUPON CODE", 500, "internalServerError");
}
}).catch(err => {
console.log("crash", err.message);
return res.fail(err.message, 500, "internalServerError");
});