Most Effective Approach for Handling Multiple Fetch Requests Concurrently using Async-Await in TypeScript?

I am currently exploring the idea of making multiple API calls simultaneously by utilizing multiple fetch requests within an await Promise.all block, as shown below:

const responseData = await Promise.all([
  fetch(
    DASHBOARDS_API +
      "getGoalsByGroupName?queryParamValues=FOOVAL0"
  ).then((response) => response.json()),

  fetch(
    DASHBOARDS_API +
      "getGroupByName?queryParamValues=FOOVAL1"
  ).then((response) => response.json().body),
]);

This method works perfectly fine, and I'm able to successfully log the responses.

However, the issue arises when each fetch response contains metadata (such as statusCode and count), but I am only interested in the actual data inside response.json().body.

When I attempt to access it like I did in the second request, TypeScript raises a complaint:

any
Property 'body' does not exist on type 'Promise<any>'. ts(2339)

What is the most efficient way to extract and store just the inner data from the responses in my responseData array immediately? If direct extraction is not possible, should I individually transform each response and then assign it to another array?

EDIT:

I forgot to mention that I am using .map along with a new array for formatting the data, but it seems a bit cumbersome compared to performing inline transformations.

Here's how I currently implement it:

const data = responseData.map(response => response.body)

Answer №1

Since Body.json() is inherently asynchronous, you cannot directly access the body property. Instead, you can use an additional then call to achieve this:

const responseData = await Promise.all([
  fetch(`${DASHBOARDS_API}getTasksByCategory?category=FOOVAL0`)
  .then((response) => response.json()),

  fetch(`${DASHBOARDS_API}getCategoriesByName?name=FOOVAL1`)
  .then((response) => response.json())
  .then((response) => response.body)
]);

JavaScript playground

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

Utilizing Typescript for manipulation of Javascript objects

Currently, I am working on a project using Node.js. Within one of my JavaScript files, I have the following object: function Person { this.name = 'Peter', this.lastname = 'Cesar', this.age = 23 } I am trying to create an instanc ...

How do I resolve validation function error messages in Vuetify?

When utilizing validation methods in Vuetify, I encountered the following error message↓ I simply want to create a form validation check and implement a function that triggers the validation when the 'submit' button is clicked. I believe my i ...

Converting the information retrieved from Firebase into a different format

My Project: In my Angular SPA, I am trying to retrieve data from Firebase and display specific values on the screen. Approach Taken: The data returned from Firebase looks like this: Returned Data from Firebase Error Encountered: In order to display the ...

Tips for showing that every field in a typed form group must be filled out

Starting from Angular 14, reactive forms are now strictly typed by default (Typed Forms). This new feature is quite convenient. I recently created a basic login form as shown below. form = this.fb.group({ username: ['', [Validators.required ...

Can an entire object be bound to a model in an Angular controller function?

In TypeScript, I have defined the following Interface: interface Person { Id: number; FirstName: string; LastName: string; Age: number; } Within a .html partial file, there is an Angular directive ng-submit="submit()" on a form element. A ...

What is causing the TypeScript error in the MUI Autocomplete example?

I am attempting to implement a MUI Autocomplete component (v5.11) using the example shown in this link: import * as React from 'react'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autoco ...

The error `TypeError: Unable to access properties of an undefined value (reading 'authService')` occurred

I'm attempting to check if a user is already stored in local storage before fetching it from the database: async getQuestion(id: string): Promise<Question> { let res: Question await this.db.collection("questions").doc(i ...

What is the best way to showcase the outcome of a function on the user interface in Angular 2?

The code snippet below was originally in my .component.html file: <div class="someContainer"> <div class="text--bold">Display this please:</div> <div>{{ myObject.date ? '2 Jun' : 'Now' }}</div&g ...

The current state of this scenario is not clearly defined within the parent class

Here is the scenario that caught my attention: abstract class Base { public _obj = { name: 'Test' } print1() { console.log(this._obj) } print2() { console.log(this) } } class Child extends Base { print2( ...

Tips for wrapping text in a column within material-ui's DataGrid

Struggling to apply word wrap to my column header title in DataGrid from material-ui. I've attempted using sx and style with no success. I even tried this: const StyledDataGridtwo = styled(DataGrid)<DataGridProps>(({ theme }) => ({ root: { ...

Error: Unable to generate MD5 hash for the file located at 'C:....gradle-bintray-plugin-1.7.3.jar' in Ionic framework

When attempting to use the command ionic cordova run android, an error occurred that prevented the successful execution: The process failed due to inability to create an MD5 hash for a specific file in the specified directory. This issue arose despite suc ...

tsconfig is overlooking the specified "paths" in my Vue project configuration

Despite seeing this issue multiple times, I am facing a problem with my "paths" object not working as expected. Originally, it was set up like this: "paths": { "@/*": ["src/*"] }, I made updates to it and now it looks like ...

Looking for guidance on locating Typescript type definitions?

As a newcomer to Typescript, I have recently delved into using it with React. While I have grasped the fundamentals of TS, I find myself perplexed when it comes to discovering or deriving complex types. For example, in React, when dealing with an input el ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

Tips for utilizing <Omit> and generic types effectively in TypeScript?

I'm currently working on refining a service layer in an API with TypeScript by utilizing a base Data Transfer Object. To prevent the need for repetitive typing, I have decided to make use of the <Omit> utility. However, this has led to some per ...

Tips for maintaining the selection when switching pages with smart-table?

I have implemented smart-table in my project to allow users to select records from different pages and view them in a preview section. However, I am facing an issue where the selection made on the first page does not persist when navigating back to it aft ...

Is it possible to apply a formatting filter or pipe dynamically within an *ngFor loop in Angular (versions 2 and 4

Here is the data Object within my component sampleData=[ { "value": "sample value with no formatter", "formatter": null, }, { "value": "1234.5678", "formatter": "number:'3.5-5'", }, { "value": "1.3495", "formatt ...

I am having trouble locating my source code within the Typescript module

My issue lies with a file called Server.js, which holds the code for export class Program and includes <reference path='mscorlib.ts'/>. However, when I compile it using the command: tsc -t ES5 Server.ts --module commonjs --out Server.js T ...

What purpose does the class serve in typescript?

This is a unique version of app.component.ts in the Angular Tour of Hero tutorial. import { Component } from '@angular/core'; export class Superhero{ name : string; id : number; } const SUPERHEROES : Superhero[] = [ {name : 'Wonder ...

Managing Events in Angular 2 and Creating Custom Event Handlers

Currently, I am in the process of developing a component library in Angular 2 for our app teams to utilize. One of the components I recently created is a modal, but I am encountering some accessibility challenges. Specifically, I want the modal to close wh ...