Martin Hinze
Martin Hinze

Reputation: 71

JS fetch API: How to fetch content from multiple files with one async function?

I would like to fetch data from multiple files with a single async function. Currently my code is like this:

const fetchExternalData = async() => {
   const resp1 = await fetch('file1.txt');
   const resp2 = await fetch('file2.txt');
   return resp1.text(); // How could I return the content from file2.txt as well?
}

fetchExternalData().then((response) => {
  console.log(response); // Data from file1.txt
  // How could I access the data from file2.txt?
}

This way, I can work with the data from the first file, but how could I access the data from more files this way? Hope the question is understandable. Any help will be greatly appreciated.

Upvotes: 1

Views: 1829

Answers (2)

goto
goto

Reputation: 4425

Here's one way you could go about this using Promise.all:

const fetchExternalData = () => {
  return Promise.all([
    fetch("file1.txt"),
    fetch("file2.txt")
  ])
  .then(
    results => Promise.all(
      results.map(result => result.text())
    )
  )
}

Then, when calling your fetchExternalData function, you will get an array of items with data from both of your files:

fetchExternalData().then(
  (response) => {
    // [file1data, file2data]
  }
)

Here's an example:

const fetchExternalData = () => {
  return Promise.all([
    fetch("https://jsonplaceholder.typicode.com/todos/1"),
    fetch("https://jsonplaceholder.typicode.com/todos/2")
  ]).then(results => {
    return Promise.all(results.map(result => result.json()));
  });
};

fetchExternalData()
  .then(result => {
    // console.log(result);
  })
  .catch(console.error);

Alternatively, if you'd want to return an object instead of an array, you could do something like the following:

const fetchExternalData = items => {
  return Promise.all(
    items.map(item =>
      fetch(`https://jsonplaceholder.typicode.com/todos/${item.id}`)
    )
  )
  .then(
    responses => Promise.all(
      responses.map(response => response.json())
    )
  )
  // use `Array.reduce` to map your responses to appropriate keys
  .then(results =>
    results.reduce((acc, result, idx) => {
      const key = items[idx].key;
      
      // use destructing assignment to add 
      // a new key/value pair to the final object
      return {
        ...acc,
        [key]: result
      };
    }, {})
  );
};

fetchExternalData([
  { id: 1, key: "todo1" }, 
  { id: 2, key: "todo2" }
])
  .then(result => {
    console.log("result", result);
    console.log('todo1', result["todo1"]);
  })
  .catch(console.error);

References:

Upvotes: 3

Night King
Night King

Reputation: 455

return multiple values by putting it in an object. like this:

const fetchExternalData = async() => {
   const resp1 = await fetch('file1.txt');
   const resp2 = await fetch('file2.txt');
   return ({res1: resp1.text(), res2: resp2.text()});
}

Upvotes: 1

Related Questions