即使我使用PROMISE和ASYNC / AWAIT结构也无法获取数据

时间:2019-02-16 13:11:24

标签: javascript node.js promise async-await es6-promise

我想先填充数组然后渲染页面,我使用async / await,但它尝试先渲染页面然后填充数组之后

控制台输出:

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

[]

.....

{     数据 }

{     数据 }

{     数据 }

{     数据 }

.....

我已经搜索并测试了所有异步/等待结构

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

我想先填充数组,然后渲染页面

0 个答案:

没有答案