Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Promise.all to fetch JSON Datas is Empty

In my code, I am trying to fetch data from two JSON files and return them as an array. I did the solution below but it didn’t work. What should I do to log those arrays on to the console and achieve what I want?

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);
  }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re over complicating the code with all those pointless async

The issue is, that x is a Promise … an unresolved Promise at the time you console.log it

try the following instead

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

constructor(private _http: HttpClient) {
    const makeRequest = (url) => fetch(url).then(response => response.json());
    
    Promise.all(this.requests.map(this.makeRequest))
    .then(x => console.log(x));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading