Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html fetch multiple files

I would like to fetch multiple files at once using the new fetch api (https://fetch.spec.whatwg.org/). Is is possible natively? If so, how should I do it leveraging the promises?

like image 763
Nicolas Avatar asked Apr 16 '15 13:04

Nicolas


People also ask

Can I use fetch in HTML?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.

What is fetch HTML?

Definition and Usage. The fetch() method starts the process of fetching a resource from a server. The fetch() method returns a Promise that resolves to a Response object.


Video Answer


2 Answers

var list = [];
var urls = ['1.html', '2.html', '3.html'];
var results = [];

urls.forEach(function(url, i) { // (1)
  list.push( // (2)
    fetch(url).then(function(res){
      results[i] = res.blob(); // (3)
    })
  );
});

Promise
  .all(list) // (4)
  .then(function() {
    alert('all requests finished!'); // (5)
  });

This is untested code! Additionally, it relies on Array.prototype.forEach and the new Promise object of ES6. The idea works like this:

  1. Loop through all URLs.
  2. For each URL, fetch it with the fetch API, store the returned promise in list.
  3. Additionally, when the request is finished, store the result in results.
  4. Create a new promise, that resolves, when all promises in list are resolved (i.e., all requests finished).
  5. Enjoy the fully populated results!
like image 143
Boldewyn Avatar answered Oct 12 '22 19:10

Boldewyn


While implementing Boldewyn's solution in Kotlin, I pared it down to this:

fun fetchAll(vararg resources: String): Promise<Array<out Response>> {
    return Promise.all(resources.map { fetch(it) }.toTypedArray())
}

Which roughly translates to this in JavaScript:

function fetchAll(...resources) {
    var destination = []
    resources.forEach(it => {
        destination.push(fetch(it))
    })
    return Promise.all(destination)
}

Earlier, I tried to use map instead of forEach + pushing to a new array, but for some reason that simply didn't work.

like image 35
Ky. Avatar answered Oct 12 '22 19:10

Ky.