首页 > 解决方案 > 从 forEach 推送对象后数组保持为空

问题描述

需要帮助,我有问题 Array Keep Empty 从 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);

提前致谢

标签: node.jsexpress

解决方案


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


推荐阅读