JAVASCRIPT

Concurrently Fetch Multiple API Endpoints with Promise.all

Learn how to efficiently make multiple API requests concurrently using `Promise.all` in JavaScript, waiting for all to complete before processing their combined results.

const BATCH_API_BASE_URL = 'https://jsonplaceholder.typicode.com';

async function fetchMultipleEndpoints(endpoints) {
    const promises = endpoints.map(endpoint =>
        fetch(`${BATCH_API_BASE_URL}/${endpoint}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`API error for ${endpoint}: ${response.status} ${response.statusText}`);
                }
                return response.json();
            })
            .catch(error => {
                console.error(`Error fetching ${endpoint}:`, error.message);
                return null; // Return null or specific error object to prevent Promise.all from failing
            })
    );

    // Promise.all waits for all promises to settle (resolve or reject)
    // If any promise rejects and isn't caught, Promise.all will reject immediately.
    // We've added .catch() to individual fetches, so Promise.all will always resolve.
    const results = await Promise.all(promises);
    return results;
}

// Usage Example:
/*
(async () => {
    try {
        const endpointsToFetch = [
            'posts/1',
            'users/2',
            'todos/3',
            // Simulate a failing endpoint
            'nonexistent-endpoint/999'
        ];

        const allResults = await fetchMultipleEndpoints(endpointsToFetch);
        console.log('All API results:', allResults);

        const [post, user, todo, failedResult] = allResults;
        console.log('Post data:', post);
        console.log('User data:', user);
        console.log('Todo data:', todo);
        console.log('Failed result:', failedResult); // Should be null due to catch
    } catch (err) {
        console.error('An unhandled error occurred in fetchMultipleEndpoints:', err.message);
    }
})();
*/
How it works: This JavaScript snippet demonstrates how to concurrently fetch data from multiple API endpoints using `Promise.all`. It takes an array of endpoint paths, maps each to an `fetch` call, and then uses `Promise.all` to wait for all these individual requests to complete. By wrapping each `fetch` promise with its own `.catch()`, `Promise.all` will always resolve with an array of results, even if some individual requests fail (in which case a `null` or error object can be returned for that specific result). This pattern is highly efficient for populating dashboards or views that require data from several independent API calls simultaneously.

Need help integrating this into your project?

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

Hire DigitalCodeLabs