Replacing a push operation in JavaScript with a splice operation

Upon entering a screen, 5 promises are automatically loaded using promise.all. The issue is that they are executed in a random order, and within each function, I use a push to store the information.

The problem arises when I need to change the push to a splice, as the promise.all loads the promises randomly and the push method does not guarantee the correct assignment of information for each "function". Below is the code snippet:

Initially, the promises are loaded:

ngOnInit(): void {
Promise.all([this.getData1(), this.getData2()]).then(values => {
            console.log(values)
            this.processing = true;
          }).catch(reason => {
            console.log('error get data',reason)
          });
}

I have only included 2 functions as an example, but the others follow the same pattern.

 public getData1() {
        return new Promise((resolve, reject) => {
            this.createService.getServiceData1().subscribe(
                (response: any) => {
                    let customFieldOption: CustomFieldOption = new CustomFieldOption();
                    this.opcionServicio = response;
                    this.opcionesServicio.push(this.opcionServicio);
                    this.servicio.push(this.opcionesServicio[0].ticket_field.title)
                    customFieldOption.id = this.opcionServicio.ticket_field.id;
                    customFieldOption.name = this.opcionServicio.ticket_field.title;
                    this.customFieldOptions.push(customFieldOption);
                    resolve(true);
                },
                (error) => {
                    console.log(error);
                    reject(true);
                }
            );
        });
    }




 public getData2() {
            return new Promise((resolve, reject) => {
                this.createService.getServiceData2().subscribe(
                    (response: any) => {
                        let customFieldOption: CustomFieldOption = new CustomFieldOption();
                        this.opcionServicio = response;
                        this.opcionesServicio.push(this.opcionServicio);
                        this.servicio.push(this.opcionesServicio[0].ticket_field.title)
                        customFieldOption.id = this.opcionServicio.ticket_field.id;
                        customFieldOption.name = this.opcionServicio.ticket_field.title;
                        this.customFieldOptions.push(customFieldOption);
                        resolve(true);
                    },
                    (error) => {
                        console.log(error);
                        reject(true);
                    }
                );
            });
        }

Answer №1

You have the option of using an array with indexes in place of the push method or an object with static keys.

For instance:

You could assign data1 to this.opcionesServicio[0] and data2 to this.opcionesServicio[1]. This way, you can always access them using the same index.

opcionesServicio = [];

public getData1(dataIndex = 0) {
  return new Promise((resolve, reject) => {
    this.createService.getServiceData1().subscribe((response: any) => {
       this.opcionesServicio[dataIndex] = response;
    });
  });
}

public getData2(dataIndex = 1) {
  return new Promise((resolve, reject) => {
    this.createService.getServiceData2().subscribe((response: any) => {
       this.opcionesServicio[dataIndex] = response;
    });
  });
}

// Access
const data1 = this.opcionesServicio[0];
const data2 = this.opcionesServicio[1];

Alternatively:

You can store the data in an object instead. Assign data1 to this.opcionesServicio['data1'] and data2 to this.opcionesServicio['data2']. This allows you to access them using the data1 and data2 keys.

opcionesServicio = {};

public getData1(dataName = 'data1') {
  return new Promise((resolve, reject) => {
    this.createService.getServiceData1().subscribe((response: any) => {
       this.opcionesServicio[dataName] = response;
    });
  });
}

public getData2(dataName = 'data2') {
  return new Promise((resolve, reject) => {
    this.createService.getServiceData2().subscribe((response: any) => {
       this.opcionesServicio[dataName] = response;
    });
  });
}

const data1 = this.opcionesServicio['data1'];
const data2 = this.opcionesServicio['data2'];

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

What steps can be taken to confirm the accuracy of input before sending it

Having trouble with validating input before submitting? Every time I run submit(), something seems to be going wrong :( const [value, setValue] = React.useState(""); const [error, setError] = React.useState(""); const validate = () => { value.length ...

JQuery tips and tricks: How to create a hover effect for an image positioned behind

Is there a way to achieve hover on an element that is positioned behind another? I am working with two images and have come across others with the same issue. However, the solutions they found were just workarounds rather than true solutions to achieving a ...

Attempting to send a request from the front-end to the back-end is resulting in a 404 endpoint error

I encountered an issue while sending a post request from the front end to the backend. The error message I received was: " Error: Request failed with status code 404 " " Had Issues POSTing to the backend, endpoint " My main concern is ...

Emphasize rows in the MUI-Datatables framework

A table was created using React.js and MUI-Datatables: import MUIDataTable from "mui-datatables"; const columns = ["Name", "Company", "City", "State"]; const data = [ ["Joe James", "Test Corp", "Yonkers", "NY"], ["John Walsh", "Test Corp", "Hartford", ...

Capture data from a Telegram bot and store it in a Google Sheet

I am trying to use a spreadsheet through a Telegram bot as a TODO list so that when I input something on my phone, it is saved in the spreadsheet. (I'm following this tutorial https://www.youtube.com/watch?v=XoTpdxbkGGk, which seems accurate with Goog ...

Set Divs in Absolute Position Relative to Each Other

I need to create a simple navigation system using <div> elements as individual pages. The goal is to have "next" and "back" buttons that allow users to switch between these pages with a smooth fade-in and fade-out effect, all powered by jQuery. Howev ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

Is my input file in Javascript valid and does it exist? Here's how to check

In my Javascript code, I am retrieving strings from a text file. When the user inputs an incorrect or invalid file name, I want to display a message. For example: console.log("Your input is invalid"); Here is the code snippet that reads the text file and ...

What is the solution to rectifying the issue with graphql codegen?

Upon running the command "yarn graphql-codegen," an error occurred and I am unsure how to resolve it: % yarn graphql-codegen yarn run v1.22.4 warning package.json: No license field $ /Users/xxx/node_modules/.bin/graphql-codegen ✔ Parse Configuration ⚠ ...

What is the best way to retrieve a value from an asynchronous method in Node.js that is using promises and also calling another asynchronous method?

I have created two methods for verifying the availability of data in a database and storing the data. The methods are as follows: function IfUserExists(userId) { logger.info(`Checking If ${userId} exists`); return new Promise(resolve => { ...

Merging double borders in a div using CSS is essential for creating

Upon examining this sample, it's evident that the borders do not blend together. css: div{ float:left; background-color:moccasin; width:100px; height:100px; border:1px solid tomato; } The number of divs is arbitrary, and only on ...

Tips for updating and transferring a variable within a callback function

I have implemented a function using the SoundCloud API that retrieves a song URL, obtains the associated sound ID from the API, and then passes that ID to a callback for streaming purposes and updating the page. The data is successfully retrieved from the ...

Error: A TypeError occurred with the startup because it was unable to read the property 'Collection' as it was

Recently, I encountered a series of problems one after another. The first issue was: TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client To resolve this problem, I made changes to my code from: const Discord = require(" ...

Creating a backup link for a video player component in NextJs

My aim is to make sure that two video player components in a NextJS application can still access and play videos even when the application is running locally using npm run dev without an internet connection. Currently, these two components.. <HoverVi ...

Using Discord.js to filter messages that start with a specific phrase and finding a solution for handling DiscordAPIError when using bulk

This is the code I am currently using. Shout out to @André Dion for the assistance. if (message.channel.type == 'text') { message.channel.fetchMessages().then(messages => { const botMessages = messages.filter(msg => msg.auth ...

If there is no data defined, then it is necessary for at least one attribute to be present in the

I am encountering an issue while attempting to utilize Google Cloud's Pub/Sub API to send messages to topic subscribers. The error message I am receiving is "If data is undefined, at least one attribute must be present.". My intention is to integrate ...

Differences in disabled option value selection between jQuery legacy and updated versions

Recently, I upgraded the jQuery version in my project from 1.7.2 to 2.1.1 and included jquery migrate for fallback support. During testing, I encountered an issue with the value of a select element in jQuery versions 2.1.1 and 1.7.2: For version 1.7.2, t ...

npm installs a multitude of dependencies

Recently, I purchased an HTML template that includes various plugins stored in a directory named bower_components, along with a package.js file. While trying to add a new package that caught my interest, I opted to utilize npm for the task. Upon entering ...

What is the most efficient way to generate a pug file with a hashed resource name using Webpack 2.0?

Here is how my file structure looks: /public (files ignored by git) /src index.js /views index.pug server.js webpack.config.js index.pug <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link href="/publi ...

Share your message with BotFramework WebChat by simply clicking on the provided link

A chatbot I created using Microsoft Bot Framework has been integrated into my website through DirectLine: <div id="chatbot_body"></div> <script src="https://unpkg.com/botframework-webchat/botchat.js"></script> <script> ...