Fetching JSON data using Promise.all results in an empty response

I'm facing an issue in my code where I am trying to fetch data from two different JSON files and then return them as arrays. Even after implementing the solution below, it doesn't seem to be working as expected. Can someone guide me on how I can successfully log those arrays onto the console?

TS:

  requests = [
    'data/products.json',
    'data/categories.json',
  ];

  constructor(private _http: HttpClient) {
    const x = Promise.all(this.requests.map((url) => fetch(url))).then(
      async (res) => Promise.all(res.map(async (data) => await data.json()))
    );
    console.log(x);
  }

Answer №1

When working with Promise.all, the returned result may appear to be "empty" (actually a Promise) if it has not resolved by the time of logging. To address this, make sure to either use await or capture the result using .then.

One approach could be to write const x = await Promise.all(...) outside of a constructor within a method, or utilize Promise.all(...).then(...).

Answer №2

Don't add unnecessary complexity to your code with excessive use of async

The problem lies in the fact that x is a Promise ... an unresolved Promise when you log it

Consider using the following approach instead

urls = [
    'data/products.json',
    'data/categories.json',
];

constructor(private _http: HttpClient) {
    const fetchData = (url) => fetch(url).then(response => response.json());
    
    Promise.all(this.urls.map(this.fetchData))
    .then(x => console.log(x));
}

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

Challenges arise when trying to coordinate scrolling movements between a canvas element and the remaining content on the webpage

I'm currently stuck on a project involving a Three.js canvas with OrbitControls for interactive 3D visualization. The main issue I'm facing is the lack of synchronization between scrolling within the canvas and the rest of the page content. Whil ...

Encountering a TypeError indicating that the asterisk is not functioning as a proper function

Whenever I run my server.js file, an error keeps popping up: TypeError: routing is not a function This occurs in the following line of code: routing(app); In my routing.js file, the content looks like this: // JavaScript source code var friends = requ ...

Guide to retrieving a .txt file from a separate domain using server-side JavaScript and transferring it to the client side

My goal is to retrieve a .txt file from a web server on a different domain that does not have CORS or web services enabled. I believe I will need to handle this task on the server side using Node.js and JQuery, but I am unsure of where to begin. Currently, ...

execute javascript code found in the html document

Currently, I have a bash script that utilizes curl to download a page. Then, it uses grep and sed to extract javascript within the html block to a file. Following this, I use node to evaluate and leverage the downloaded javascript. Here is an example: cur ...

The Nextjs framework is experiencing a high total blocking time in its *****.js chunk

As I analyze the performance of next.js in my project, I am noticing a high total blocking time. Specifically, the "framework" chunk consistently takes more than 50ms. It seems that this chunk corresponds to the react and react-dom JavaScript files. Does ...

Extract information from a JSON file and import it into an Angular TypeScript file

How can I retrieve data from a JSON file and use it in an Angular typescript file for displaying on web pages? this.http.get<any>('http://localhost:81/CO226/project/loginResult.json').subscribe((res: Response)=>{ }); Here ...

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

Encountering an Invalid JSON error on the Developer console

I'm in the process of building a React application and aiming to establish a connection with my Back4App database. Within the Back4App dashboard, there exists a Person class containing data that needs to be retrieved. It appears that the call is being ...

Creating a custom comparison method between two select dropdowns using the jQuery Validation plugin

In my HTML code, I have two select elements: <label for="h_slat_type">Horizontal Slat Type</label> <select name="h_slat_type" id="h_slat_type"> <option disabled="disabled" selected>Select</option> ...

Adjust the href attribute of a link dynamically using the value input from a text field immediately

Is there a way to dynamically change the href attribute of a link when a user types in an input field? And is it possible to detect when a user pastes content into the input field as well? Would appreciate any suggestions on how to accomplish this using j ...

Why is my Angular form submitting twice?

Currently, I am working on a user registration form using AngularJS with ng-submit and ng-model. However, I am facing an issue where the form triggers submission twice when the user submits it. I have checked for common causes such as declaring the contro ...

Animating a dotted border path in SVG for a progress bar effect

I am attempting to create an animation for a dotted SVG circle that resembles a progress bar, where it fills itself over a duration of 3 seconds. However, I am facing difficulties in achieving this effect with the dotted border. The current code I have doe ...

Modify the background color of the entire page when the main div is clicked

I am attempting to alter the background color of my entire page when the div with id main is clicked. You can view the code here: $(document).ready(function() { var color = 1; $('#main').click(function(){ if (colo ...

Include an option for whitespace characters when validating a file using regex

My text box has specific criteria for what is considered good or bad input. Examples of good input could include: GoodString GoodString88 99GoodString I want to avoid certain types of bad input, such as: Good*String Good&String However, I do want ...

Setting the selected value of a radio button in an edit form: a step-by-step

I'm currently developing an edit form using ReactiveFormModule. My goal is to display data in the edit form with various input elements such as textboxes, dropdowns, radio buttons, and checkboxes. I've been successful in setting values for textbo ...

I have a JSON object with a nested "src" value that I want to display on my webpage using Vue. How can I target and select this specific value?

I am currently working with an API and attempting to access a nested object within the JSON data named "Species Illustration Photo". Inside this object is an "img" property with the source link. How can I display this nested img source in my HTML using Vue ...

Angular template in PhpStorm displaying error: Unresolved pipe issue

I am currently working on a project generated by Angular CLI version 7.3.9 (Angular version 7.2.0) and using IDE: PhpStorm version 2019.1.2. Within the template of my component, I am utilizing the UpperCasePipe: <h2>{{ title | uppercase }}</h2&g ...

I'm having trouble utilizing toastify.js after installing it via npm. I keep receiving the error message "Failed to resolve module specifier." Any advice

Currently, I am attempting to utilize Toastify-js, a library designed for toast type messages, by installing it through npm. In the provided documentation, following the execution of the installation command, there is a direction that states: - To begin ...

Insert information into a 3-tiered nested Angular FormArray within interconnected dropdown fields

After trying to retrieve data from an API call to populate a select form field, I encountered difficulties setting the value correctly using a FormArray. This led me to creating a FormArray with 3 nested levels in Angular, taking reference from this examp ...

What is the best way to link a specific version of the @types package to its corresponding JavaScript package version?

Currently, I am in the process of working on a nodejs project with typescript 2.2 that relies on node version 6.3.1. My goal is to transition from using typings to utilizing @types. However, during this migration, several questions have arisen regarding th ...