Tips for effectively managing asynchronous tasks

I keep getting different numbers every time my code runs. Can you tell me if I'm doing this the right way? Here's the code:

export class GetPlanetsService {
  url='https://swapi.co/api/planets/?page=';
  planets:Planet[]=[];
  headers: HttpHeaders = new HttpHeaders()
    .set('Accept', 'application/json');

  constructor(private http:HttpClient) { }


  getPlanet(pageIndex){                                          
    return this.http.get<Planets>(`${this.url}${pageIndex}`,{headers:this.headers});
  }
  getAllPlanets(){
    let numberOfPages=7;  
    for(let j=1;j<=numberOfPages;j++){
      this.getPlanet(j).subscribe(value=>{
        for(let i=0;i<value.results.length;i++){
          this.planets.push(value.results[i]);
          if(j==numberOfPages && i==(value.results.length-1)){
            console.log(this.planets); 
          }
        }     

    });

    }
  } 

Can you provide any guidance and explain it in simple terms? Thanks

Answer №1

To handle multiple HTTP requests, you should consider using the forkJoin method. Make sure to import it in your code:

import { forkJoin } from 'rxjs';

When using forkJoin, each HTTP request will be awaited until completion. The result is an array of observables that can be merged into a single observable array.

getPlanet(pageIndex) {
        return this.http.get < Planets > (`${this.url}${pageIndex}`, {
            headers: this.headers
        });
    }

    getAllPlanets() {
        const response = [...Array(7).keys()].map(i => this.getPlanet(i));
        return forkJoin(response);
    }

In your component, invoke the getAllPlanets function like so:

this.getPlanetsService.getAllPlanets()
    .subscribe(res => {
      console.log(res);
    }, err => {
      console.log(err);

 });

Answer №3

There seems to be a deeper issue at play here.

First and foremost, why are you attempting to make 7 consecutive server calls? What if I need information from page 200? Will you send out 200 separate Http requests? It would be more efficient for the server to return the entire list in one go, improving performance and simplifying things on the client side.

Furthermore, why does getAllPlanets() have a return type of void? This can be confusing. Instead, getAllPlanets() should ideally return Observable<Planet[]>. Following the Command Query Separation principle, functions should either return data or modify state. In this case, the function's purpose is to retrieve data, so modifying the object's state like

this.planets.push(value.results[i])
may lead to unexpected behavior when invoking the function multiple times.

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

Troubleshooting: Images not displaying on webpage due to Ajax, JQuery, and JavaScript integration

I'm currently working on building a dynamic photo gallery using Ajax and JQuery in Javascript. I have set up a directory named "images" in Visual Studio Code and it contains my selection of 5 images. However, when I click the "next" and "previous" but ...

Having trouble closing my toggle and experiencing issues with the transition not functioning properly

Within my Next.js project, I have successfully implemented a custom hook and component. The functionality works smoothly as each section opens independently without interfering with others, which is great. However, there are two issues that I am facing. Fi ...

When using Next.js revalidate, an error may occur stating: "There are keys that require relocation: revalidate

I have been attempting to utilize the revalidate function in my code by following the example provided by Vercel. However, I keep encountering an error. Here is the snippet of code that I am currently using: export async function getServerSideProps() { c ...

Encountering numerous issues during my attempt to perform an npm install command

After cloning a git repository, I encountered an issue when trying to run the app in the browser. Despite running "npm install," some dependencies were not fully installed. Upon attempting to run "npm install" again, the following errors were displayed: np ...

Utilize ngx-translate with an array as interpolation values

When working with ngx-translate, I use the instant method to translate messages into the user's language. These messages are provided as JSON objects and some of them contain dynamic values: { "message.key": "First value is {{0}} and se ...

This method or property is not supported by the object - How to call an Applet in Internet Explorer 9

cmd > java -version Java Version : "1.7.0_11" (Updated) Java(TM) SE Runtime Environment (build 1.7.0_11-b21) Java HotSpot(TM) Client VM (build 23.6-b04, mixed mode, sharing) browsers = IE7,IE8,IE9 (The functionality works smoothly in Google Chrome and ...

Error: Failed to parse the given color specification

My chrome extension is showing an error message: Unchecked runtime.lastError: The color specification could not be parsed. This error seems to be in the popup.html: 1 -> <! DOCTYPE html> line. Can anyone explain what this means and how to fix it? ...

Vue and Nuxt: Concealing a Variable in .env File Post-Build

     Within my Nuxtjs project, I have implemented a process in which I encrypt requests before they are sent to my Laravel API. Once the response is received, I decrypt it using specific global functions that have been defined... function encryptDataLa ...

Utilize JSON data to dynamically populate TextFields or Select menus depending on a specific key in the JSON object

As I retrieve multiple JSON groups from an API, each group contains one or more questions objects. The task at hand is to attach each question along with its corresponding response to a textField. Based on the value of QuestionType, it will be decided whet ...

NodeJS Socket not transmitting file after connection with client

Having scoured the depths of various resources, including SO and Google, I have hit a roadblock. I am struggling to understand why the socket is failing to capture the uploaded file via the form; it simply stops after connecting. When I check the console, ...

The MDX blog was set up to showcase markdown content by simply displaying it without rendering, thanks to the utilization of the MDXProvider from @mdx-js/react within Next JS

I'm currently in the process of setting up a blog using MDX and Next.js, but I've encountered an issue with rendering Markdown content. The blog post seems to only display the markdown content as plain text instead of rendering it properly. If y ...

Encountering an error in TypeScript and ng2 rc.1: Error message (20, 15) TS2304 indicates that the name 'module' cannot be found

Having trouble with TypeScript and ng2 rc.1 - getting Error:(20, 15) TS2304: Cannot find name 'module'. I encountered this issue when trying to use a directive of the module in my code: @Component({ selector: 'Notes1', moduleI ...

Converting a JSON object into a format suitable for transmission through AJAX requests

I am attempting to transmit data in a JSobject via AJAX using jQuery. Below is the json object: var cookieData = { 'land' : document.URL, 'ref' : document.referrer }; The object is then stored in a cookie... throu ...

Converting JSON-style data into a string with the power of node mysql

Just a quick note - I'm a total newbie in the world of web development, so I might be missing an obvious solution here. My challenge is to insert a dataset into a MySQL database using nodejs/expressjs/mysql. I've managed to establish a connecti ...

How to stop a checkbox from being selected in Angular 2

I have a table with checkboxes in each row. The table header contains a Check All checkbox that can toggle all the checkboxes in the table rows. I want to implement a feature where, if the number of checkboxes exceeds a certain limit, an error message is ...

Discovering the value of an item when the editItem function is triggered in jsGrid

Within my jsGrid setup, I have invoked the editItem function in this manner: editItem: function(item) { var $row = this.rowByItem(item); if ($row.length) { console.log('$row: '+JSON ...

Swapping out the initial occurrence of every word in the list with a hyperlink

I stumbled upon a fantastic script on a programming forum that almost fits my requirements perfectly. It essentially replaces specific words in a document with links to Wikipedia. However, I have run into an issue where I only want the first occurrence of ...

What is the reasoning behind CoffeeScript automatically adding a function when extending an Object?

I'm currently working on a helper method to identify the intersection of two hashes/Objects in this manner... Object::intersect = (obj)-> t = {} t[k] = @[k] for k of obj t x = { a: 1, b: 2, c: 3 } w = { a: true, b: 3 } x.intersect(w) #=> ...

Transform text that represents a numerical value in any base into an actual number

Looking to convert a base36 string back to a double value. The original double is 0.3128540377812142. When converting it to base 36: (0.3128540377812142).toString(36); The results are : Chrome: 0.b9ginb6s73gd1bfel7npv0wwmi Firefox: 0.b9ginb6s73e Now, h ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...