JAVASCRIPT

Perform Concurrent API Requests with Batching

Optimize API integrations by sending multiple requests concurrently using Promise.all in Node.js, effectively batching operations to improve performance.

const axios = require('axios'); // For making HTTP requests

async function fetchMultipleResourcesConcurrently(resourceIds) {
    const BASE_URL = 'https://jsonplaceholder.typicode.com/posts/'; // Example API
    const requests = resourceIds.map(id =>
        axios.get(`${BASE_URL}${id}`)
            .then(response => ({ id, status: response.status, data: response.data }))
            .catch(error => ({ id, status: error.response ? error.response.status : 'N/A', error: error.message }))
    );

    console.log(`Attempting to fetch ${resourceIds.length} resources concurrently...`);

    try {
        const results = await Promise.all(requests);
        console.log('All concurrent requests completed.');
        return results;
    } catch (error) {
        // This catch block would typically only be hit if Promise.all fails fast
        // due to a severe error before all promises settle.
        // With the individual .catch() on each request, Promise.all usually waits for all to settle.
        console.error('An unexpected error occurred during concurrent fetching:', error.message);
        throw error;
    }
}

// --- Example Usage ---
(async () => {
    const idsToFetch = [1, 2, 3, 4, 5];
    try {
        const fetchedData = await fetchMultipleResourcesConcurrently(idsToFetch);
        fetchedData.forEach(result => {
            if (result.error) {
                console.error(`Error fetching ID ${result.id}: Status ${result.status}, Error: ${result.error}`);
            } else {
                console.log(`Successfully fetched ID ${result.id}. Title: "${result.data.title.substring(0, 30)}..."`);
            }
        });
    } catch (e) {
        console.error('Main execution failed:', e);
    }

    console.log('
--- Example with a non-existent ID (simulating a 404 error) ---');
    const idsWithError = [10, 9999, 11]; // 9999 will likely return a 404
    try {
        const fetchedDataWithError = await fetchMultipleResourcesConcurrently(idsWithError);
        fetchedDataWithError.forEach(result => {
            if (result.error) {
                console.error(`Error fetching ID ${result.id}: Status ${result.status}, Error: ${result.error}`);
            } else {
                console.log(`Successfully fetched ID ${result.id}. Title: "${result.data.title.substring(0, 30)}..."`);
            }
        });
    } catch (e) {
        console.error('Main execution failed for error example:', e);
    }
})();
How it works: This Node.js snippet demonstrates how to "batch" multiple independent API requests by sending them concurrently using `Promise.all`. While not a true single "batch endpoint" request (which some APIs provide), this approach significantly reduces the total time required to fetch multiple resources compared to sequential requests. Each individual request is wrapped in a Promise that handles its own success or failure, allowing `Promise.all` to wait for all promises to settle (either fulfilled or rejected) and return an array of all results. This is highly effective for improving perceived performance in scenarios where an API doesn't offer a dedicated batching endpoint.

Need help integrating this into your project?

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

Hire DigitalCodeLabs