在 sequelize 结果后,Nodejs 中的数组打印为空

Array print empty in Nodejs after sequelize result

我正在尝试将数据库结果的输出推送到一个名为 'array' 的变量中。但是在该过程结束时,我在控制台中得到一个空值。但是在 'then' 函数内部,数据来了。 data.foreach 的大小约为 30。我正在使用 Nodejs 14 和 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);

您似乎在 forEach 循环中有多个 await。您的循环不会按预期工作,因为 forEach 会触发多个异步调用。当您必须在循环中处理异步操作时,这不是正确的方法。

你应该使用可以帮助你实现它的for..of

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

注意:如果您使用 async/await,请不要将其与 then/catch 混合使用,反之亦然。