Create a function that fetches data from multiple URLs concurrently and returns the results when all have completed.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Logic/Approach:
This is a perfect use case for Promise.all().
1. Map each URL in the input array to a fetch Promise. Inside the .then() of each fetch, parse the response (e.g., as JSON).
2. Use Promise.all() to wait for all of these fetch Promises to resolve.
3. The result of Promise.all() will be an array containing the resolved values (the parsed data) from all the URLs, in the same order.
4. Use async/await for cleaner syntax.
async function fetchDataFromUrls(urls) {
try {
const fetchPromises = urls.map(url =>
fetch(url).then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
);
const results = await Promise.all(fetchPromises);
return results;
} catch (error) {
console.error("Error fetching data:", error);
// Depending on requirements, you might want to return null, an empty array, or re-throw.
throw error;
}
}
// Example usage:
const API_URLS = [
'https://jsonplaceholder.typicode.com/posts/1',
'https://jsonplaceholder.typicode.com/posts/2'
];
fetchDataFromUrls(API_URLS)
.then(data => console.log("Fetched data:", data))
.catch(err => console.error("Failed to fetch all data."));