Concurrent Data Fetching from Multiple APIs using Promises and Promise.all()
JavaScript Asynchronous: Exercise-6 with Solution
Write a JavaScript function that fetches data from multiple APIs concurrently and returns a combined result using Promises and 'Promise.all()'.
Sample Solution:
JavaScript Code:
function fetchDataFromAPI(url) {
return fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
});
}
function fetchMultipleAPIs(apiUrls) {
const promises = apiUrls.map(url => fetchDataFromAPI(url));
return Promise.all(promises);
}
// Example usage:
const apiUrls = [
'https://jsonplaceholder.typicode.com/posts/4',
'https://jsonplaceholder.typicode.com/posts/5',
'https://jsonplaceholder.typicode.com/posts/6'
];
fetchMultipleAPIs(apiUrls)
.then(results => {
console.log('Combined Results:', results);
})
.catch(error => {
console.log('Error:', error.message);
});
Output:
"Combined Results:" [[object Object] { body: "ullam et saepe reiciendis voluptatem adipisci sit amet autem assumenda provident rerum culpa quis hic commodi nesciunt rem tenetur doloremque ipsam iure quis sunt voluptatem rerum illo velit", id: 4, title: "eum et est occaecati", userId: 1 }, [object Object] { body: "repudiandae veniam quaerat sunt sed alias aut fugiat sit autem sed est voluptatem omnis possimus esse voluptatibus quis est aut tenetur dolor neque", id: 5, title: "nesciunt quas odio", userId: 1 }, [object Object] { body: "ut aspernatur corporis harum nihil quis provident sequi mollitia nobis aliquid molestiae perspiciatis et ea nemo ab reprehenderit accusantium quas voluptate dolores velit et doloremque molestiae", id: 6, title: "dolorem eum magni eos aperiam quia", userId: 1 }]
Note: Executed on JS Bin
Explanation:
In the above exercise -
The "fetchMultipleAPIs()" function takes an array of API URLs as a parameter. It maps over the URLs and creates an array of Promises by calling fetchDataFromAPI for each URL.
Promise.all() is used to wait for all the Promises in the array to resolve. It returns a new Promise that resolves with an array of the resolved values from each Promise.
In the example usage, an array of API URLs is provided, and fetchMultipleAPIs is called with that array. The resulting Promise is then handled with .then() to log the combined results or with .catch() to handle any errors that occur during the fetching process.
Flowchart:
Live Demo:
See the Pen javascript-asynchronous-exercise-6 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Asynchronous Exercises Previous: Sequential Asynchronous Operations in JavaScript using Promises and async/await.
Asynchronous Exercises Next: JavaScript Function for Retrying API Requests with Automatic Retry.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/javascript-exercises/asynchronous/javascript-asynchronous-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics