从forEach推送对象后,数组保持为空

时间:2020-06-09 04:14:20

标签: node.js express

需要帮助,我遇到问题数组保持为空从forEach中推入对象后,我会错过吗?这是代码:

const allStatus = [];
    result.forEach(async (element) => {
      const count = await BpCandidate.count({
        where: {
          applicationStatusId: element.id
        },
        raw: true,
      });
      })  
      record = {
        id: element.id,
        name: element.name,
        code: element.code,
        description: element.description,
        total: count
      };
      allStatus.push(record);
    });
    console.log(allStatus);

预先感谢

3 个答案:

答案 0 :(得分:1)

使用for...of对您有用,但是如果您使用Promise.all

可以在这里看到改进。

const allStatus = await Promise.all(result.map(async (element) => {
  const count = await BpCandidate.count({
    where: {
      applicationStatusId: element.id
    },
    raw: true,
  });
  return  {
    id: element.id,
    name: element.name,
    code: element.code,
    description: element.description,
    total: count
  };
}))

答案 1 :(得分:0)

首先,您需要在foreach部件的外部范围内定义element变量以获得所需的结果,这是帮助程序代码段:

    const allStatus = [];
    result.forEach(async (element) => {
      const count = await BpCandidate.count({
        where: {
          applicationStatusId: element.id
        },
        raw: true,
      });
      record = {
        id: element.id,
        name: element.name,
        code: element.code,
        description: element.description,
        total: count
      };
      allStatus.push(record);
      })  
    });
    console.log(allStatus);

答案 2 :(得分:0)

每个

都不会执行异步任务,也不会解决诺言。 用于of或Promise。所有循环迭代。

const allStatus = [];
for(let element of result) {
  const count = await BpCandidate.count({
    where: {
      applicationStatusId: element.id
    },
    raw: true,
  });
  })  
  record = {
    id: element.id,
    name: element.name,
    code: element.code,
    description: element.description,
    total: count
  };
  allStatus.push(record);
});
console.log(allStatus);