Search code examples
htmlstandardsfetch-api

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?


Solution

  • 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!