0

I am trying to create a filtered array in an array of objects. I am doing so by running case switch in a forEach and deriving a new array attaching that to a new object and pushing that object to an array stored outside of the foreach. but after running the foreach the length of the external array still shows 0 and the rest of the equation relates to the processing of said array. Its two very large blocks of code so i've tried to redact some.

let updatedDrop = []
  drop.forEach(async(tollFree) => {

      const zipCodes = Object.values(tollFree)[0].split(",");
   

      let updatedList = []
      const {
        tracking,
        mailList,
      } = tollFree;

   zips = await Zip.find({
    "class": { "$in": zipCodes },
  });
   
  zips = zips.map(zip => zip.zip4)

switch (zipCodeSuppress) {
  case "keepSelect":
   (insert case switch)
    break;
}

  const distinct = (value, index, self) => {
    return self.indexOf(value) === index;
  };
      updatedList = updatedList.flat()

      updatedList = updatedList.filter(distinct)
      

   const combinedCost = unitCost + postageCeiling
   const  dropItem = {
        updatedList,
        tracking,
     } 
      
     updatedDrop.push(dropItem)

     //console.log(dropItem)
    })


console.log(updatedDrop.length)

  let advJobs = [];
  let cspJobs = [];
  let wbJobs = [];
if (updatedDrop.length > 0){ ..... 

so until i am able to access the updated asynchronous data the rest of the formula is stalled. How do I do this?

Mickey Gray
  • 440
  • 2
  • 11

1 Answers1

0

The problem you are facing is that the forEach callback doesn't block the main thread, so at the moment you access the array right after the declaration of the forEach, the callback inside didn't finish executing.

Look at this example

const timer = 2000;
const numbers = [1, 2, 3];
const emptyArray = [];

async function getNumberTwo() {
  return new Promise((resolve) => {
    setTimeout(() => resolve(2), timer);
  });
}

async function withForEach() {
  numbers.forEach(async (n) => {
    const two = await getNumberTwo();
    emptyArray.push(n + two);
  });
  console.log(emptyArray); // the array is empty here.
  setTimeout(() => console.log(emptyArray), numbers.length * timer); // if I log the array after all the time has gone, the array has the numbers.
}

withForEach()

but now if you use for of, or even a normal for I would say

// all the declarations from before..

async function withForOf() {
  for (const number of numbers) {
    const two = await getNumberTwo();
    emptyArray.push(number + two);
  }

  console.log(emptyArray); // now the array has what you expect it to have
}

withForOf()

So, in conclusion, you can use a normal for or a for of to make it work as you need.

Mario
  • 64
  • 4