user15974743
user15974743

Reputation:

Fetching multiple things

Let' say we want to fetch three files. We can do this by:

fetch("./1.json")
  .then((response) => {
    return response.json();
  })
  .then((text_1) => {
    fetch("./2.json")
      .then((response) => {
        return response.json();
      })
      .then((text_2) => {
        fetch("./3.json")
          .then((response) => {
            return response.json();
          })
          .then((text_3) => {
            console.log("Done")
        });
      });
  });

But this nesting will over complicatet the code. Are there any work-arounds for this?

They can all be fetched at the same time OR sequentially

Upvotes: 0

Views: 116

Answers (4)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48610

If they need to be handled in series, you could create individual callbacks for each:

const handleResponse1 = (text_1) =>
  fetch("./2.json").then(res => res.json()).then(handleResponse2);

const handleResponse2 = (text_2) =>
  fetch("./3.json").then(res => res.json()).then(handleResponse3);

const handleResponse3 = (text_3) => console.log("Done");

fetch("./1.json").then(res => res.json()).then(handleResponse1);

If you want all the responses simultaneously, you can destructure the Promise.all result.

const requests = [
  'https://jsonplaceholder.typicode.com/posts/1',
  'https://jsonplaceholder.typicode.com/posts/2',
  'https://jsonplaceholder.typicode.com/posts/3'
];

const fetchJson = async (request) =>
  fetch(request).then(response => response.json());

const fetchJsonAll = async (requests) =>
  Promise.all(requests.map(fetchJson));

(async () => {
  const [ res1, res2, res3 ] = await fetchJsonAll(requests)
    .catch(err => console.log(err.message));

  console.log(JSON.stringify(res1));
  console.log(JSON.stringify(res2));
  console.log(JSON.stringify(res3));
})();
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 1

ManuelMB
ManuelMB

Reputation: 1375

  const allPromises = [fetch("./1.json"), fetch("./2.json"), fetch("./3.json")]
 
  Promise.all(allPromises).then((values) => {
    console.log(values);
  });

Upvotes: 1

Phoenix1355
Phoenix1355

Reputation: 1652

A simple solution would be to use Promises like so:

Promise.all([
  fetch("./1.json").then((response) => response.json()),
  fetch("./2.json").then((response) => response.json()),
  fetch("./3.json").then((response) => response.json()),
]).then((values) => console.log(values));

It should log the responses as an array, e.g.:

["res1", "res2", "res3"]

Upvotes: 4

theusaf
theusaf

Reputation: 1802

You could make use of a loop as well as async/await:

async function fetchStuff() {
  const files = ["./1.json", "./2.json", "./3.json"];
  for (let i = 0; i < files.length; i++) {
    const result = (await fetch(files[i])).json();
  }
  console.log("Done");
}
fetchStuff();

Upvotes: 0

Related Questions