Home > Net >  Is there a good way to loop through APIs?
Is there a good way to loop through APIs?

Time:12-11

There are too many loops in this API, which is causing it to run slowly. this data is only for year i have to run same code for Day month week looping same code makes the code slower.

// ```GRAPH CALCULATION FOR YEAR```\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
let query = '';
graph_data = '';
let startOfYear = MOMENT().startOf('year');
let monthsForYear = [];
let year = [];
// Create an array of dates representing the start of each month in the year
for (let index = 0; index <= 11; index  ) {
  const add1Month = MOMENT(startOfYear)
    .add(index, 'month')
    .format('YYYY-MM-DDTHH:mm:SS.000 00:00');
  monthsForYear.push(add1Month);
}
// Get the actual amount for each month
for (let i = 0; i < monthsForYear.length; i  ) {
  let j = i   1;
  let d = await PRISMA.orders.findMany({
    where: {
      created_at: {
        gte: monthsForYear[i],
        lte:
          i === monthsForYear.length - 1 ? endOftheYear_date : monthsForYear[j],
      },
    },
    select: { actual_amount: true },
  });
  // Calculate the total actual amount for the month
  let total = 0;
  d.forEach((el) => {
    total  = el.actual_amount;
  });
  year.push(total);
}

// Set the graph data to the calculated amounts
graphDataOfYear = year;

CodePudding user response:

You execute asynchronous statements (using await) in a loop, which means they are executed consecutively: The second statement starts only after the first has completed. It may be faster if you execute them in parallel.

The first loop starts all statements in parallel, then all results are awaited together and the total actual amounts calculated in a second loop:

let statements = [];
for (let i = 0; i < monthsForYear.length; i  ) {
  let j = i   1;
  statements.push(PRISMA.orders.findMany({
    where: {
      created_at: {
        gte: monthsForYear[i],
        lte:
          i === monthsForYear.length - 1 ? endOftheYear_date : monthsForYear[j],
      },
    },
    select: { actual_amount: true },
  }));
}
for (const d of await Promise.all(statements)) {
  // Calculate the total actual amount for the month
  let total = 0;
  d.forEach((el) => {
    total  = el.actual_amount;
  });
  year.push(total);
}

The general pattern is:

let statements = [];
for (...) {
  statements.push(/* asynchronous statement without await */);
}
for (const d of await Promise.all(statements)) {
  /* d is the result of each asynchronous statement in turn */
}

It is very likely even faster if you can let PRISMA do the total actual amount calculation, because then only one number (the total actual amount) must be sent back to your Javascript code, whereas with your current code every order that exists in PRISMA is sent back for one of the months, and then again for one of the weeks, and for one of the days. But I am no PRISMA expert.

  • Related