0

i want to first fill the array and then render the page, i use async/await but it is trying first render the page and then after fill the array

Console Output:

 --*--*--*--*--*--*--*-- Render --*--*--*--*--*--*--*--

[]

.....

{ Data }

{ Data }

{ Data }

{ Data }

.....

I've searched and tested all async/await structures

Shares.findAll({

        limit: 12,
        offset: (req.params.page - 1) * 12,
        order: [
            ['createdAt', 'DESC']
        ]
    })
    .then(shared => {

        function loop(){
            shared.forEach(data => {
                if(data.dataValues.tableName === 'Pr'){
                    async function add(){  
//It is coming here but doesn't anything and going to outside the function
                        let product = await Products.findOne({where: {ID: data.dataValues.shareID}});
                        return product.dataValues;
                    }
                    add().then(data => {
                        console.log(data)
                        allData.push(data);
                    });
                }else if(data.dataValues.tableName === 'Nt'){
                    async function add(){
//It is coming here but doesn't anything and going to outside the function
                        let note = await Notes.findOne({where: {ID: data.dataValues.shareID}});
                        return note.dataValues;
                    }
                    add().then(data => {
                        console.log(data)
                        allData.push(data);
                    });
                }else if(data.dataValues.tableName === 'Ad'){
                    async function add(){
//It is coming here but doesn't anything and going to outside the function
                        let advertisement = await Advertisements.findOne({where: {ID: data.dataValues.shareID}});
                        return advertisement.dataValues;
                    }
                    add().then(data => {
                        console.log(data)
                        allData.push(data);
                    });
                }
            });
        }
        async function proccess(){
            await loop();
            await Promise
                .resolve(allData)
                .then(data => {
                    console.log('--*--*--*--*--*--*--*-- Render --*--*--*--*--*--*--*--')
                    console.log(data)
                    if(typeof data !== 'undefined')
                        if(data.length > 0)
                            res.render('home', {title: 'Anasayfa', Data: data, Count: page, Page: req.params.page});
                });
        }
        proccess();
    })
    .catch(error => {
        console.log(error);
        res.redirect(url.format({
            pathname: '/hata',
            query:{
                errorMessage: error.errors[0].message
            }
        }));
    });

I want to first fill the array and then render the page

crazycoder
  • 39
  • 6

0 Answers0