DEV Community

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

Posted on

3 1

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/

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay