1

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

Console

1 Answers1

1

There are a couple of things wrong about your code.

  1. You are using async-await inside a arr.map() function, which will not block the main thread and your res.json({message : 'Order placed!'}) will get called before your array elements are processed. Use a 'for' loop with await to block your main thread.

    Solution- https://pouchdb.com/2015/03/05/taming-the-async-beast-with-es7.html

2.You are sending multiple responses to the client for a single request which is not allowed and therefore you are getting the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11). Change your code in such a way that it only sends one response for the incoming request.

Solution- https://stackoverflow.com/a/48123354/8393975

Naveen Chahar
  • 561
  • 3
  • 10