Home > Mobile >  Array print empty in Nodejs after sequelize result
Array print empty in Nodejs after sequelize result

Time:01-08

I am trying to push the output of database results into a variable called 'array'. But I get an empty value in my console at the end of the process. But inside of the 'then' function, the data is coming. the size of the data.foreach is around 30. I am using Nodejs 14 and sequelize 4.

                let array=[];
                data.forEach(async element => {
                await SelectedTech.findAll({ where: { Requirement_id: element } }).then(async data => {
                    array.push(data);

                }).then(async data => {
                    array.push(data);
                });

                await SelectedDomains.findAll({ where: { Requirement_id: element } }).then(async data => {
                    array.push(data);

                }).then(async data => {
                    array.push(data);
                });

                await SelectedRoles.findAll({ where: { Requirement_id: element } }).then(async data => {
                    array.push(data);

                }).then(async data => {
                    array.push(data);
                });

                await SelectedQualifications.findAll({ where: { Requirement_id: element } }).then(async data => {
                    array.push(data);

                }).then(async data => {
                    array.push(data);
                });


            });
      console.log(array);

CodePudding user response:

It seems you have multiple await in the forEach loop. Your loop won't work as expected because forEach trigger multiple async calls. It is not the right way when you have to deal with async operations in a loop.

You should use for..of that can help you achieve it.

const array=[];

for (const da of data) {

const data = await SelectedTech.findAll({ where: { Requirement_id: element } });
array.push(data);

const data1 = await SelectedDomains.findAll({ where: { Requirement_id: element } });
array.push(data1);

const data2 = await SelectedRoles.findAll({ where: { Requirement_id: element } })
array.push(data2);

const data3 = await SelectedQualifications.findAll({ where: { Requirement_id: element }})
array.push(data3);

}
console.log(array);

Note: If you use async/await don't mix it with then/catch and viceversa.

  •  Tags:  
  • Related