Home > Software engineering >  Why items are not being pushed in array
Why items are not being pushed in array

Time:07-08

I am using MongoseDB in order to receive some information about an item. When i try to search for it, it finds it with no trouble, but for some reasons this function is not pushing them into my array. I think this might be because of some async functions and that the console.log() is triggered before any item is being pushed in there.

const getOrders = function(allOrders){
    let promise = new Promise((succ, fail)=>{
        let ordersTodisplay = []
        for (let order of allOrders) {
            if (!(order.orderId === null || order.orderItem === null)){
                postMong.findById(order.orderItem, function (err, item) {
                    ordersTodisplay.push(item) 
                })
            }  
        } 
        if(ordersTodisplay.length > 0){
            succ(ordersTodisplay)    
        } else{
            fail("no items")
        }
    })
    return promise
}
router.get('/accountpage',function(req,res){ 
    const userDB = req.session.username
    if (userDB !== undefined && userDB){
        userForm.findOne({ username : userDB }, function (err, user) {
            const userOrders = user.userOrders;
            if (userOrders.length > 1) {
                getOrders(userOrders).then((result)=>{console.log(result)}, (fail)=>{console.log(fail)})
                res.render('../view/accountpage',{username: userDB,orders: itemsToDisplay});
            }
            else{
                res.render('../view/accountpage',{username: userDB,orders: "There are no orders"});
            }
        });
    } else {
        res.redirect("/login")
    }
});

The result is : no items

CodePudding user response:

You have to for the database call to complete and then push the data in the array like this, using async-await:

const getOrders = function(allOrders){
    let promise = new Promise(async (succ, fail)=>{
        let ordersTodisplay = []
        for (let order of allOrders) {
            if (!(order.orderId === null || order.orderItem === null)){
                await postMong.findById(order.orderItem, function (err, item) {
                    ordersTodisplay.push(item) 
                })
            }  
        } 
        if(ordersTodisplay.length > 0){
            succ(ordersTodisplay)    
        } else{
            fail("no items")
        }
    })
    return promise
}
  • Related