Tips for optimizing the performance of nested for loops

I wrote a for loop that iterates over 2 enums, sending them both to the server, receiving a value in return, and then calculating another value using a nested for loop. I believe there is room for improvement in this code snippet:

const paths = [];
for await (let category of Object.values(CategoriesEnum)) {
    for await (let format of Object.values(FormatsEnum)) {
        const totalPosts = await getPagesCount(category, format);
        const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
        for (let page = 1; page <= totalPages; page++) {
            paths.push({ params: { category: category , format: format, page: page } });
        }
    }
}
return paths;

My primary objective is to reduce execution time, although I acknowledge that the server will still receive the same number of queries so any improvements might be marginal at best. Thank you for your consideration.

Answer №1

To streamline multiple asynchronous operations, consider utilizing [Promise.all][1].

Below is a snippet for reference.

let promises = [];
let paths = [];

Object.values(CategoriesEnum).forEach(category => {
    Object.values(FormatsEnum).forEach(format => {
        promises.push(getPagesCount(category, format))
    })
});

const totalPostCounts = await Promise.all(promises);

totalPostCounts.forEach(totalPosts => {
    const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
    for (let page = 1; page <= totalPages; page++) {
        paths.push({ params: { category: category, format: format, page: page } });
    }
});

return paths;

[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Alternative Method using Same Techniques

let promises = [];
let paths = [];

/*
Aggregate API calls
*/
Object.values(CategoriesEnum).forEach(category => {
    Object.values(FormatsEnum).forEach(format => {
        promises.push(getPath(category, format))
    })
});

// Await completion of all the calls
const pathsArray = await Promise.all(promises);

// Flatten the array
pathsArray.forEach(pathArray => {
    paths = paths.concat(pathArray)
});

async function getPath(category, format) {
    let paths = [];

    const totalPosts = await getPagesCount(category, format);
    const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
    for (let page = 1; page <= totalPages; page++) {
        paths.push({ params: { category: category, format: format, page: page } });
    }

    return paths;
}

Answer №2

To start off, I suggest breaking down the logic into 3 key parts:

  1. Setting up asynchronous calls
  2. Handling async calls concurrently
  3. Implementing the necessary business logic
const pagesPromises = []
for (let category of Object.values(CategoriesEnum)) {
  for (let format of Object.values(FormatsEnum)) {
    pagesPromises.push(getPagesCount(category, format))
  }
}

const totalPostsResults = await Promise.all(pagesPromises)

const paths = [];
totalPostsResults.forEach(totalPosts => {
  const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
  for (let page = 1; page <= totalPages; page++) {
    paths.push({ params: { category: category , format: format, page: page } });
  }
})

return paths;

Answer №3

To simplify the code and utilize Promise.all(), you can implement the following without extensive modifications:

const getStaticPaths = async () => {
  const paths = [];
  const promises = [];

  Object.values(CategoriesEnum).forEach((category) => {
    Object.values(FormatsEnum).forEach((format) => {
      promises.push(async () => {

        const totalPosts = await getPagesCount(category, format);
        const totalPages = Math.ceil(totalPosts.offsetPagination.total / 12);
        for (let page = 1; page <= totalPages; ++page)
          paths.push({ params: { category: category, format: format, page: page } });

      });
    });
  });

  await Promise.all(promises);
  return { paths };
};

export { getStaticPaths };

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Send information to the next route using Vue

Within my Vue frontend, there is a method called `moveToOrder` which asynchronously communicates with the backend to process a move from the cart collection to the orders collection: methods:{ async moveToOrder() { const res = await this.$axios.g ...

Exploring values within an array of objects using Node.js

I have some data presented in the following format [ [ '@test','1.2.6' ], [ '@test2','4.0.1' ], [ '@test3','2.2.0-unstable' ], ... ] My goal is to extract all values that include -unstable, ...

Programmatically simulating a click on a link within a Windows Universal Windows Platform (U

I am facing an issue with a code that has multiple items with the same href attribute due to it being an external source. I need help figuring out how to programmatically click on a specific link tag using C# within a WebView or by accessing the source d ...

JavaScript onClick event not functioning properly on iOS devices

I have created a code that can detect when a user clicks on a cell in a table and retrieves the background color set for that cell. Everything works perfectly on my desktop computer, but when I attempt to use my iPad, it does not respond. I attempted to u ...

Tips for preventing the use of website URLs as variables in jQuery ajax() calls:

Having some trouble. For example: $(document).ready(function () { $("#btnSend").click(function () { var noti_p = { url: "Pusher_Controller.ashx", data: "&appname=" + $("#selt1").val() + "&title=" + $("#title"). ...

Issue with Date Picker not properly storing selected date in MySQL database

My goal is to save the datepicker date to MySQL by selecting the date format using JavaScript. I have verified that the date format appears correct as YYYY-MM-DD when logging to the console. However, when I try to execute an INSERT query to MySQL, the date ...

Issue with VueJS rendering data within a for loop

As a newcomer to VueJS, I appreciate your patience as I navigate through this. Let me provide as much detail as possible. I am currently working on a Vue app that needs to retrieve a response from a server, iterate through the data, and set a Vue data var ...

Ensuring that each object in a list contains an optional key if any one object includes it is a task handled by Joi validation

My dataset includes various objects that must have certain keys: Date, Time, Price I am looking to include an optional key "order" for these objects. If one of them has the "order" key, then they all should. Is there a way to validate this using joi? ...

I desire to incorporate a subtle fading effect into the script

I have written the script code and now I am looking to add a fade effect to it. Can anyone guide me on how to achieve this? Your help is much appreciated! â€ğI used an online translator as English is not my native language. Please bear with any awkward ph ...

Ember.js: Storing function prototypes as objects

My interface consists of four vertical panels: The first panel displays the menu for selecting data The second panel allows you to choose a filter from a list The third panel shows the results based on the selected filter The fourth panel displays detail ...

Exporting and importing modules in Angular 1 using Webpack 2

Seeking clarification on why the current implementation is not working as expected. It seems like a simple oversight, especially since it works fine without Webpack. I prefer to stick with the current implementation, where each component/controller/etc is ...

The error message "The useRef React Hook cannot be invoked within a callback function" is displayed

I'm currently working on developing a scroll-to feature in Reactjs. My goal is to dynamically generate referenced IDs for various sections based on the elements within an array called 'labels'. import { useRef } from 'react'; cons ...

Techniques for dynamically counting rows in a table using JavaScript

I'm working on a system to create and delete rows, and I want each row to have a unique row number displayed under "Num." However, I'm having trouble implementing this feature. EDIT I found a jQuery snippet that counts the first row but not t ...

Troubleshooting MongoDB query criteria in Meteor and JavaScript doesn't yield the expected results

I am encountering an issue with a Products collection that has an attribute called "productCode". My goal is to create a server-side query to fetch a product based on the productCode attribute. Unfortunately, I keep running into a "cannot read property &ap ...

The struggle of accessing child components using ViewChild in Angular

I am facing an issue with a dialog box that is supposed to display a child component separately. Below is the code for the child component: @Component({ selector: 'userEdit', templateUrl: './edituser.component.html', styleUrls: [ ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

Encountering an Issue with Dynamic Imports in Cypress Tests Using Typescript: Error Loading Chunk 1

I've been experimenting with dynamic imports in my Cypress tests, for example using inputModule = await import('../../__tests__/testCases/baseInput'); However, I encountered an issue with the following error message: ChunkLoadError: Loading ...

The method .setArray has been deprecated in THREE.BufferAttribute. Instead, please use BufferGeometry .setAttribute for unindexed BufferGeometry operations

Seeking assistance with updating the webgl-wireframes library code to the latest version of threejs. The current function is generating the following errors: Uncaught TypeError: THREE.Geometry is not a constructor THREE.BufferAttribute: .setArray has ...

update the componentWillMount() function

I am currently exploring the code found at https://github.com/Spyna/react-store/blob/master/src/createStore.js What adjustments do I need to make in order to align with the deprecated componentWillMount lifecycle method? CreateStore const createStore = ...

Error occurred in Flask due to request names being dynamically generated using JavaScript

My current project involves creating an app that calculates transit projections based on input years and other variables. I've written a JavaScript script where users can add new types of vehicles, each generating a unique div with specific ids and na ...