I Try to post an order. I get product's details as array of object(in that array I get product id and quantity). I'm using map function to iterate. Using id I here find all details of the product. Then I am doing before placing an order i am checking stock value and update it. When i try to send more than one object i am getting anUnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11)
How can i solve this warning.And Also another is is stock condition is not working. eg:`If stock is 0 then it should give res.(404) intstead i'm getting 200 ok status
//2.Create a Order
router.post('/orders', (req,res) => {
//products is a array of object we get from frontend
const { products,name,mobile,pincode,address,district,email } = req.body;
if(!products || !name || !mobile || !pincode || !address || !district || !email) return res.sendStatus(409).json({message:'Fields cannot be empty'});
//Using map method to itreate each object in array
products.map( async product => {
try {
const orderedItem = await Product.findById(product.id);
const currentOrder = new Order({
productId:orderedItem.productId,
quantity: product.quantity,
orderId: orderedItem.orderId,
name,
mobile,
pincode,
address,
district,
email
});
//Stock updating
if(orderedItem.stock <= 0){
console.log('stock less or equal to is checking...');
return res.sendStatus(404).json({message:'oops! Product Out of Stock'});
}
if(currentOrder.quantity > orderedItem.stock){
console.log('remove product condition is checking')
return res.status(404).json({message:orderedItem.name+'Please remove the product'});
} //return res.sendStatus(404)//.json({message:'Quantity you choose is not available please try using less quantity'});
orderedItem.stock = orderedItem.stock-currentOrder.quantity;
await orderedItem.save();
await currentOrder.save();
// await sendEmail(orderedItem,currentOrder);
} catch (error) {
return res.sendStatus(500).json({message:error});
}
});
res.json({
message : 'Order placed!'
});
});