What is the best way to divide data prior to uploading it?

I am currently working on updating a function that sends data to a server, and I need to modify it so that it can upload the data in chunks.

The original implementation of the function is as follows:

    private async updateDatasource(variableName: string, variableRecords: ChartDataResponse[]):Promise<boolean> {
    // unrelated code
        return this.portalService.updateDataForChart(variableId, variableRecords)
            .then((updateRes: boolean) => {
                 if (updateRes) {
                    return this.executeRequest<HealthDataSource, boolean>({
                      path: `/variable/user/datasources/${dataSource.identifier}`,
                      method: 'PUT',
                      body: {
                        libelle: dataSource.datasource.libelle,
                        type: dataSource.datasource.type,
                        lastSyncDate: Math.max(maxDate, dataSource.datasource.lastSyncDate)
                      },
                      headers: this.getHeaders()
                    });
                  } else {
                    return false;
                  }
                });
            } else {
              return Promise.reject(false);
            }
          }

I have attempted the following approach, but I am struggling with how to properly return a promise with the desired result:

    private async updateDatasource(variableName: string, variableRecords: ChartDataResponse[]): Promise<boolean> {
    //unrelated code 
    //chunked the data
          var chunks = _.chunk(variableRecords, 30);

          return _.forEach(chunks, (chunk) => this.portalService.updateDataForChart(variableId, chunk))
            .then((updateRes: boolean) => {
              if (updateRes) {
                return this.executeRequest<HealthDataSource, boolean>({
                  path: `/variable/user/datasources/${dataSource.identifier}`,
                  method: 'PUT',
                  body: {
                    libelle: dataSource.datasource.libelle,
                    type: dataSource.datasource.type,
                    lastSyncDate: Math.max(maxDate, dataSource.datasource.lastSyncDate)
                  },
                  headers: this.getHeaders()
                });
              } else {
                return false;
              }
            });
        } else {
          return Promise.reject(false);
     }
    }

Answer №1

If you're looking to retrieve a list of promise results, one approach is to utilize the Promise.all() method.

In your specific scenario, rather than utilizing the forEach function, you can create an array of promises like this:

Promise.all(
   chunks.map(chunk => this.portalService.updateDataForChart(variableId, chunk)))...
).then(results => {
   // Process the results array and perform additional tasks
})

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

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

Positioning Firefox absolutely within a table-cell element is possible

Interestingly, it's not Internet Explorer causing me trouble this time, but Firefox. Here is the Fiddle link for reference: http://jsfiddle.net/EwUnt/ The purpose of this table is to highlight both the row and column of the cell where the cursor is ...

Why am I encountering difficulties connecting to the Socket IO object in Node.js using Express?

Encountering a strange issue on the remote server side where everything works fine locally with a self-signed cert over https. However, when moving the code to the server, it works locally but not remotely. A node app is created and hosted on the server u ...

What are the steps to add code into the Monaco Editor using Playwright?

As I explore the world of Playwright, I am faced with a challenge regarding testing a feature that involves a monaco editor. Unfortunately, my search in Playwright documentation and forums did not yield any relevant information. Here is the test scenario ...

Is it possible to verify the data within a VueJS model? It seems that none of the Vue validators are effective

Hello there, It's common knowledge that using Vue-validator with most UI components can be challenging when it comes to validation. I've been utilizing Vue Material Components by @mjanys, which is a fantastic library. The author has included met ...

Implementing ESM in your next.config.js file is critical for optimizing

Currently, I am in the process of optimizing a Next.js project and came across the requirement to include type: 'module' in thepackage.json file. However, this led to an error being thrown: Error [ERR_REQUIRE_ESM]: Must use import to load ES Mo ...

Breaking down a intricate JavaScript expression in order to reformat it into a different structure

As I explore the task of refactoring a legacy application, I find myself faced with complex JavaScript expressions stored in a database column. These expressions contain validation and conditional rendering logic that need to be translated into structured ...

Warning: Next.js is throwing a hydration error because the server HTML does not include a matching <main> element within a <div>

I have been encountering hydration issues in my next.js application. After extensive troubleshooting, I have found that the culprit might be the higher order component called withAuth.js The error message displayed is: Warning: Expected server HTML to con ...

Can one designate something as deprecated in TypeScript?

Currently, I am in the process of creating typescript definitions for a JavaScript API that includes a deprecated method. The documentation mentions that the API is solely for compatibility purposes and has no effect: This API has no effect. It has been ...

Utilize Moment.js in AngularJS for formatting dates

I have been attempting to use moment.js in Angularjs to format a date, but it seems like I am running into some issues. Here is the link to my code snippet on jsfiddle http://jsfiddle.net/sed6x5e8/ and below you can find the HTML and JS code that I am work ...

I keep running into a problem that says "Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))". I've been unable to come up with a solution so far

const Header = () => { const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{user}, dispatch] = useStateValue(); const login = async () =>{ const { user: { refreshToken, providerData }, } = await sign ...

Unable to send multiple cookies using custom headers in Next.js configuration

I am using custom headers to set the cookie in my next.config.js file. The refresh token is successfully set, but for some reason the second token is not being recognized. key: 'Set-Cookie', value: `RefreshTokenKey = " ...

Step-by-step guide to creating a custom wrapper in React that modifies the props for a component

Exploring React components for the first time and seeking assistance. I am interested in dynamically wrapping one component inside another and modifying its props. For instance, considering the following component: If we want to pass the key3 from a wrapp ...

I'm having trouble getting my CSS opacity to smoothly transition back to its original state of .5 using setTimeout(). What could be

I recently started learning JS, Jquery, and CSS. My goal is to create a Simon Says style game. However, when I attempt to animate the computer to automatically light up the correct square, I faced some challenges. To address this issue, I decided to star ...

Encountered an error while using JSON.parse(): `SyntaxError: Unexpected token in JSON at position 0`

As I embark on my Node.js development journey, I am faced with a challenge while trying to retrieve data from a JSON file. An error message interrupts my progress: SyntaxError: Unexpected token  in JSON at position 0 at Object.parse (native) Below is ...

Can Mongoose handle document arrays editing and version control efficiently?

Currently working on a web application using Node.js and MongoDB/Mongoose, the main model in our project is Record which contains numerous subdocument arrays such as "Comment", "Bookings", and "Subscribers". However, when users click the delete button in ...

Mapping Form Fields (with Formik)

Currently, the Formik/Yup validation setup in my form is working perfectly: export default function AddUserPage() { const [firstName, setFirstName] = useState(""); const [email, setEmail] = useState(""); return ( <div> <Formik ...

Angular 8's array verification feature lacks the ability to recognize preexisting elements

I've been trying to add and delete items in an array when a user selects or deselects the same item. However, it appears that either my array is not working properly or there is a bug in my code causing it to fail. <div class="grp-input"> ...

Combining Django with the powerful Vue3 and lightning fast Vite

I'm in the process of upgrading my multipage app from Vue2 with webpack to Vue3 with Vite. After successfully rendering my Vue3 components on my Django templates, I am now facing a challenge - setting component variables on the Vue app using the Djan ...

Tips for creating a page component in Next.js using props?

I've encountered an issue while trying to properly annotate the parameters of the Home function component. My initial attempt was to use: { events }: { events: Event[] }, but TypeScript is throwing an error, stating that Property 'events' do ...