Array ForEach, but queries get executed only once

Hi,

I was able to solve it after some help from @joeBumbaca during Discord Office Hours on Thursday.

This is what is working.

const array = createArray.value;

const stepSize = 100 / array.length
let progressCount = 0
progress.setValue(0)

const promises = array.map(async (item) => {
  const ccodes = await getCcode.trigger({
    additionalScope: {
      mescno: parseInt(item),
    },
  });

  let ccode1_details = null;
  let ccode2_details = null;

  if (ccodes.ccode1 !== '') {
    const details = await getCcodeDetails.trigger({
      additionalScope: {
        ccode: ccodes.ccode1[0],
      },
    });
    ccode1_details = details[0];
  }

  if (ccodes.ccode2 !== '') {
    const details = await getCcodeDetails.trigger({
      additionalScope: {
        ccode: ccodes.ccode2[0],
      },
    });
    ccode2_details = details[0];
  }
  
  progressCount = progressCount + stepSize
  progress.setValue(progressCount)
  
  return {
    mescno: parseInt(item),
    mesc_desc: ccodes.usc_short_desc[0],
    ccode1: ccodes.ccode1[0],
    ccode1_descript: ccode1_details ? ccode1_details.DESCRIPT : null,
    ccode1_qty: ccode1_details ? parseFloat(ccode1_details.QTY_STK_AVAIL) : null,
    ccode1_pffcost: ccode1_details ? parseFloat(ccode1_details.CUSTOM_STOCK_COST) : null,
    ccode2: ccodes.ccode2[0],
    ccode2_descript: ccode2_details ? ccode2_details.DESCRIPT : null,
    ccode2_qty: ccode2_details ? parseFloat(ccode2_details.QTY_STK_AVAIL) : null,
    ccode2_pffcost: ccode2_details ? parseFloat(ccode2_details.CUSTOM_STOCK_COST) : null,
    smart_price: ccodes.smart_price['0'],
    leadtime: ccodes.leadtime['0'],
  };

});

const json = await Promise.all(promises);

return json;

Massive speed improvement using async.
I'm going to try to speed things up further by querying the PostgresDB for all the ccodes at once , so it doesn't need to make separate queries and then merge/join it using JS.

3 Likes