2

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.