JAVASCRIPT

Batching Multiple Independent API Requests with JavaScript `Promise.all`

Optimize performance by sending multiple independent API requests concurrently using JavaScript's `Promise.all`, waiting for all to complete before processing.

async function fetchMultipleResources() {
  const postId = 1;
  const userId = 2;
  const productId = 3;

  const postPromise = fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`).then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
  });
  
  const userPromise = fetch(`https://jsonplaceholder.typicode.com/users/${userId}`).then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
  });

  const productPromise = fetch(`https://fakestoreapi.com/products/${productId}`).then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
  });

  try {
    console.log('Initiating concurrent API calls...');
    const [postData, userData, productData] = await Promise.all([
      postPromise,
      userPromise,
      productPromise
    ]);

    console.log('All API calls completed successfully:');
    console.log('Post Data:', postData);
    console.log('User Data:', userData);
    console.log('Product Data:', productData);

    // You can now use all the fetched data together
    return { postData, userData, productData };
  } catch (error) {
    console.error('One of the API calls failed:', error);
    // Handle individual promise rejections here if necessary, or just re-throw
    throw error;
  }
}

// Call the function to execute the batch requests
fetchMultipleResources();
How it works: This snippet demonstrates an efficient way to make multiple independent API requests concurrently using `Promise.all` in JavaScript. Instead of sending requests sequentially, which would take longer, `Promise.all` allows you to initiate all promises (e.g., `fetch` calls) at roughly the same time. It then waits for all of them to resolve. If all promises succeed, it returns an array of their results in the same order as the input promises. If any promise in the array rejects, `Promise.all` immediately rejects with the reason of the first promise that rejected, providing robust error handling for batch operations.

Need help integrating this into your project?

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

Hire DigitalCodeLabs