w3resource

Optimize API Fetching: Parallel vs Sequential Methods Explained


Parallel vs Sequential Fetch:

Write a JavaScript program to fetch data from multiple APIs first in parallel and then sequentially, comparing their performance.

Solution-1: Parallel Fetch

Code:

async function fetchInParallel(urls) {
  const startTime = performance.now(); // Start measuring time

  // Use Promise.all to fetch all URLs in parallel
  const results = await Promise.all(urls.map((url) => fetch(url).then((res) => res.json())));

  const endTime = performance.now(); // End measuring time
  console.log(`Parallel fetch completed in ${(endTime - startTime).toFixed(2)} ms`);
  return results;
}

// Example usage for parallel fetch
const urls = [
  'https://jsonplaceholder.typicode.com/posts/1',
  'https://jsonplaceholder.typicode.com/posts/2',
  'https://jsonplaceholder.typicode.com/posts/3',
];

fetchInParallel(urls).then((results) => console.log('Parallel Results:', results));

Output:

"Parallel fetch completed in 894.50 ms"
"Parallel Results:"
[[object Object] {
  body: "quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto",
  id: 1,
  title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  userId: 1
}, [object Object] {
  body: "est rerum tempore vitae
sequi sint nihil reprehenderit dolor beatae ea dolores neque
fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis
qui aperiam non debitis possimus qui neque nisi nulla",
  id: 2,
  title: "qui est esse",
  userId: 1
}, [object Object] {
  body: "et iusto sed quo iure
voluptatem occaecati omnis eligendi aut ad
voluptatem doloribus vel accusantium quis pariatur
molestiae porro eius odio et labore et velit aut",
  id: 3,
  title: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
  userId: 1
}]

Explanation:

  • 'Promise.all' ensures all fetches are initiated simultaneously.
  • Each fetch is converted to JSON and resolved in parallel.
  • Execution time is logged to compare with sequential fetch.

Solution-2: Sequential Fetch

Code:

async function fetchSequentially(urls) {
  const startTime = performance.now(); // Start measuring time

  const results = [];
  for (const url of urls) {
    const response = await fetch(url); // Wait for each fetch to complete
    const data = await response.json(); // Convert response to JSON
    results.push(data); // Store the result
  }

  const endTime = performance.now(); // End measuring time
  console.log(`Sequential fetch completed in ${(endTime - startTime).toFixed(2)} ms`);
  return results;
}

// Example usage for parallel fetch
const urls = [
  'https://jsonplaceholder.typicode.com/posts/1',
  'https://jsonplaceholder.typicode.com/posts/2',
  'https://jsonplaceholder.typicode.com/posts/3',
];


// Example usage for sequential fetch
fetchSequentially(urls).then((results) => console.log('Sequential Results:', results));

Output:

 "Sequential fetch completed in 113.50 ms"
"Sequential Results:"
[[object Object] {
  body: "quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto",
  id: 1,
  title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  userId: 1
}, [object Object] {
  body: "est rerum tempore vitae
sequi sint nihil reprehenderit dolor beatae ea dolores neque
fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis
qui aperiam non debitis possimus qui neque nisi nulla",
  id: 2,
  title: "qui est esse",
  userId: 1
}]

Explanation:

  • Each fetch is performed one at a time using a `for` loop.
  • The next fetch starts only after the previous one completes.
  • Execution time is logged to compare with parallel fetch.

Key Differences:

  • Parallel fetch executes all fetches at the same time, reducing overall duration.
  • Sequential fetch executes one fetch at a time, increasing overall duration.
  • Use parallel fetch when possible for better performance, but sequential fetch may be necessary when order matters or APIs have rate limits.

See the Pen promises-and-async-await-exercise-19 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Cancelable Promises in JavaScript with Practical Examples.
Next:Implementing Chained retries with increasing Delays in JavaScript.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.