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

Issue encountered when displaying various data options in the dropdown menus within a modal window

My goal is to display a modal when a button is clicked. The modal renders perfectly fine, but I am facing an issue with duplication of dropdowns inside the modal when the "add more" button is clicked. The main issues are: 1. Selecting the first option in ...

How can I replace any non-alphanumeric characters in a string with an underscore using JavaScript or TypeScript?

There is a unique string generated from an external data source that I cannot manage. The system above me necessitates the IDs to adhere to this rule: "Field names should start with a letter and can solely consist of letters, numbers, or underscores (&apos ...

Updating Angular view based on service parameter change

In-depth Inquiry I have a specific setup with a header view and a main view in my Angular application. The goal is to include a "back" button in the header that should only be visible based on the current page I'm viewing. Actions Taken In my app ...

Can data be filtered based on type definitions using Runtime APIs and TypeDefs?

My theory: Is it feasible to generate a guard from TypeDefs that will be present at runtime? I recall hearing that this is achievable with TS4+. Essentially, two issues; one potentially resolvable: If your API (which you can't control) provides no ...

Implementing a dynamic star rating system in Angular

I am working with an array of ratings that looks like this: "rating": [ { "sno": 1, "question": 13, }, { "sno": 2, ...

Can you pass a generic type as a parameter for another generic in Java?

Simply provide a generic type like a callback: type FUNC<ARG,RET, F> = (arg: ARG) => F<RET>; type PROMISE<T> = Promise<T>; type IDENT<T> = T; type A = FUNC<number, void, IDENT>; type A_PROMISE = FUNC<number, void, ...

Why am I not receiving the expected feedback after submitting a request for a specific parameter in a Node.js and Express Router REST API?

Developed a Node module utilizing the Express router to facilitate the routes for the dishes REST API. Index.js file: const express = require('express'); const http = require('http'); const morgan = require('morgan'); const b ...

React checkbox remains checked even after uncheckingIs this revised version

I am currently working on a React application where I display an array of matches as a list of rows. Each row contains two athletes, and users can use checkboxes to predict the winner for each match. Only one athlete per row can be checked. To keep track o ...

Having difficulty attaching events to Bootstrap 3 button radios in button.js

Struggling with extracting the correct value from a segmented control created using the radio button component of button.js in Twitter Bootstrap 3. Upon binding a click event to the segmented control and running $.serialize() on its parent form, I noticed ...

Tips for using an array as a jQuery selector in JavaScript

Managing an element with an array id id="x[]" can be tricky when it comes to dynamically changing content based on database entries. This specific element is essentially a delete button for removing table rows from the database. <div align="center" id= ...

Traverse a tree structure of nested child objects in an Angular template using a JavaScript

Check out the Javascript object below: { "id": "1554038371930_ajhnms9ft", "name": "CPS", "nodes": [ { "id": "1554038905938_le34li2cg", "name": "Consumer Journey", "nodes": [ { ...

Exploring the efficacy of unit testing on Express controllers

After days of working on this, I've hit a wall and finally decided to ask for assistance. Everything runs smoothly when the server is up and API calls are made. However, when attempting to unit test the controller, I encounter some issues. I'm ...

Angular chat integration

In my application, I have a parent component called "chat" with two child components - "sidebar" (which displays the user list) and "conversation detail" (which shows the chat with each user). The functionality I am aiming for is that when a user is clicke ...

Looking to set an object value as optional in JavaScript?

Hello, I am currently in the process of developing a web application using ReactJS with Auth0 for user authentication. In order to update user information on my backend, I am utilizing state to store the necessary data. My challenge lies in allowing eith ...

The npm outdated -g command is producing an error message that states "Unable to read the length property of undefined"

I am currently facing an issue while trying to check the version status of my npm installed global packages. When I run the command npm outdated -g --depth=0 in the terminal, I encounter the following error: npm ERR! Cannot read property 'length&apos ...

I constantly encounter the error message "Unable to access properties of undefined (reading 'map')"

I am in the process of using Nextjs 13 for developing my front end and I have a requirement to fetch a .json file from a URL and utilize it to populate my website through server side rendering. However, I keep encountering an error saying "Cannot read prop ...

Using AngularJS to create interactive popups within leaflet maps

My map uses leafletjs to create markers such as ev124, ev125, and so on. In addition, there are links with a key attribute like <a ng-click="popup(evsi)" key="124">link</a> Using angular, I extract the key value this way: $scope.popup= funct ...

Converting object values to strings is a common practice during JSON posting operations

I encountered an issue with a date object when sending it to a NodeJS server. While the object is still preserved, the time gets converted to a string during the process. Is there a way to prevent this conversion? I tried parsing the object but received an ...

No results found by Mongoose find() method

I've set up a route that utilizes a model named Todo as shown below: app.get('/api/todos', function(req, res) { Todo.find({},function(err, todos) { if (err) res.send(err); console.log("number of todos " + tod ...

Order JSON object based on designated Array

I'm looking to organize a JSON object in a specific order, Here is the current object structure: { "you": 100, "me": 75, "foo": 116, "bar": 15 } I would like to rearrange this object in the following sequence ['me', 'foo', &apos ...