1

Need Help, I have problem Array Keep Empty After pushing object from forEach, do I miss something ? here's the code :

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

Thanks in advance

6
  • Do you get the output for result? Commented Jun 9, 2020 at 4:37
  • yes I Get the output for result @RajaShekar, but for the allStatus it's empty array only [] Commented Jun 9, 2020 at 4:38
  • 1
    Does this answer your question? Using async/await with a forEach loop Commented Jun 9, 2020 at 4:55
  • 1
    result.forEach doesn't wait for the async functions to resolve. Commented Jun 9, 2020 at 4:56
  • 1
    Also bluebird provides useful array helpers like .map Commented Jun 9, 2020 at 5:02

3 Answers 3

2

Using for...of is working for you, but can see an improvement here if you use 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
  };
}))

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

1 Comment

@NelvanBalthazar My bad, forgot to update to use map instead of forEach. Please check my updated comment.
1

for each doesn't perform async task and doesn't resolve promises. Use for of or Promise.All the loop iterations.

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

Comments

1

first you need to define element variable in outer scope of foreach part to get the desired result, here is the helper code snippet:

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

Comments

Your Answer

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