0

I'm trying to map through an array that is returned by mongoose.find() method and i want to push certain objects after querying them from the database and i want to send the resultant array to the response in node . But inside the map method if i log the array , the array is getting updated properly , but if i log it outside the map , the array is empty .

const getProductDetails = async(productId) => {
return new Promise(async(resolve,reject) => {
    try{
        const matchedProduct = await Product.findById(productId);
        resolve(matchedProduct._doc);
    }catch(err){
        reject({message:err});
    }
})

}

const getUserOrders = async (userId) => {
    const resArray = [];
    try{
        const userOrders = await Orders.find({userId:userId})
        userOrders.map(order => {
            order.Products.map(product => {
                getProductDetails(product.ProductId)
                    .then(response => {
                        console.log(response)
                        const productObj = {
                            ...response,
                            Date:order.Date,
                            isOrderProcessed:order.isOrderProcessed,
                            isOrderShipped:order.isOrderShipped,
                            isOrderDelivered:order.isOrderDelivered
                        }
                        resArray.push(productObj);
                    })
                    .catch(err => console.log(err))
            }) 
        })
        return resArray;
    }catch(err){
        console.log(err);
        return {message:err}
    }
}

router.get('/getOrders/:userId',async(req,res) => {
    try{
        const userOrders = await getUserOrders(req.params.userId);
        res.status(200).send(userOrders);
    }catch(err){
        res.status(400).send({message:err});
    }
});

Before i send the array , if i try to log the array , the array is empty . But after pushing the orderObj inside the array if i try to log the array , it gets updated correctly after each step . Can anyone tell me what i'm doing wrong ?

  • Please see [How do I return the response from an aynchronous call](https://stackoverflow.com/q/14220321/438992), which this duplicates. – Dave Newton May 04 '21 at 14:43
  • @DaveNewton Could you please tell me what's the mistake ? As i am already using asynchronous javascript to await the response before sending – vipul devnani May 04 '21 at 14:55

0 Answers0