DEV Community

Cover image for Fetch multiple API requests in vanilla JS
sanderdebr
sanderdebr

Posted on

Fetch multiple API requests in vanilla JS

It is very common in Javascript to fetch some data from an API. But what if you want to fetch many requests and only perform actions when they are all are resolved? In this article I will explain briefly how to fetch data from an API in vanilla JS (ES6) and also how to handle MANY API requests.

First, let's start with a simple API fetch. I will wrap my function in an IIFE and only expose the init method, so that from the outside the function can not be controlled and our variables and methods our private.

Make sure to set the function to asynchronous by adding the async keyword. Also always wrap your fetches inside a try-catch block to avoid breaking your application and detecting what went wrong.

Also notice how I'm storing constant values in a seperate private object that we can access only inside our myApp function. Always try to structure data and keep it modular.

const myApp = (function() {
    const constants = {
        data: document.getElementById('data')
    }

    const fetchData = async () => {
        constants.data.innerText = 'fetching data...';
        try {
            const response = await fetch("https://pokeapi.co/api/v2/pokemon/1")
                             .then(response => response.json());
          data.innerText = response.name;
        } catch (error) {
            console.error(error);
        }
    }

    const init = () => {
        fetchData();
    }

    return {
        init: init
    }
})();

<div id="data"></div>

myApp.init();

Not too bad, right?

Now what if we want to fetch data from hundreds of API request and wait until they are all finished? We will do this using Promise.all() which will loop over an array of urls, in this case 25:

const myApp = (function() {  
    const fetchData = async () => {

        let urls = [];
        for (let i = 0; i < 25; i++) {
           urls.push('https://pokeapi.co/api/v2/pokemon/');
        }

        try {
            const response = Promise.all(urls.map((url, i) =>
                  fetch(url+i).then(resp => resp.json())
              )).then(json=> {
                  console.log(json)
              })
        } catch (error) {
            console.error(error);
        }
    }

    const init = () => {
        fetchData();
    }

    return {
        init: init
    }
})();

myApp.init();

Cool, right? Hope you've learned something, have fun fetching data from API's!

Here is a free list of API's you can play around with: https://apilist.fun/

Top comments (0)