JAVASCRIPT

Execute Multiple API Requests Concurrently

Optimize web applications by concurrently sending multiple API requests using JavaScript's Promise.all, significantly reducing data loading times.

async function fetchMultipleEndpoints(urls, options = {}) {
    try {
        const fetchPromises = urls.map(url =>
            fetch(url, options).then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status} from ${url}`);
                }
                return response.json();
            })
        );

        const results = await Promise.all(fetchPromises);
        return results;
    } catch (error) {
        console.error("One or more requests failed:", error.message);
        throw error;
    }
}

// Example Usage:
// const endpoints = [
//     'https://jsonplaceholder.typicode.com/posts/1',
//     'https://jsonplaceholder.typicode.com/users/1',
//     'https://jsonplaceholder.typicode.com/comments/1'
// ];

// fetchMultipleEndpoints(endpoints)
//     .then(data => {
//         console.log('All data fetched:', data);
//         const [post, user, comment] = data;
//         console.log('Post:', post);
//         console.log('User:', user);
//         console.log('Comment:', comment);
//     })
//     .catch(err => console.error('Failed to fetch multiple endpoints:', err));
How it works: This JavaScript function `fetchMultipleEndpoints` demonstrates how to make several independent API requests concurrently using `Promise.all`. It takes an array of URLs and an optional `options` object for the `fetch` API. For each URL, it creates a `fetch` promise. `Promise.all` then waits for all these promises to resolve (or for the first one to reject). This approach drastically reduces the total time required to fetch data from multiple endpoints compared to making requests sequentially, as the browser or Node.js runtime can handle them in parallel. If any of the individual requests fail, `Promise.all` will immediately reject, and the error will be caught.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs