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

  • Do you get the output for result? – Raja Shekar Jun 09 '20 at 04:37
  • yes I Get the output for result @RajaShekar, but for the allStatus it's empty array only [] –  Jun 09 '20 at 04:38
  • 1
    Does this answer your question? [Using async/await with a forEach loop](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop) – Matt Jun 09 '20 at 04:55
  • 1
    `result.forEach` doesn't wait for the async functions to resolve. – Matt Jun 09 '20 at 04:56
  • 1
    Also bluebird provides useful array helpers like [.map](http://bluebirdjs.com/docs/api/promise.map.html) – Matt Jun 09 '20 at 05:02
  • Thanks for help @Matt im using ```for … of```` it's now working –  Jun 09 '20 at 05:03

3 Answers3

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
  };
}))
Tony Nguyen
  • 3,298
  • 11
  • 19
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);

amdev
  • 6,703
  • 6
  • 42
  • 64
Satish Chandra Gupta
  • 2,970
  • 1
  • 22
  • 22
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);
Waleed Shafiq
  • 414
  • 3
  • 10