Open In App

How to fetch an array of URLs with Promise.all ?

In this article, we will learn how to fetch an array of URLs with Promise. all ( ).

When you need information from various websites quickly, Promise.all() is your go-to tool. It’s like having a checklist of website links and using Promise.all() it to swiftly retrieve data from each link at the same time. Basically, it waits for all the tasks to finish before neatly handing you the combined results, saving you time and effort. It’s a smart way to efficiently gather data from multiple sources without delays.



Approach

Syntax:

array of URLs to fetch data from
const urlsToFetch = ['URL1', 'URL2'];
// Map URLs to fetch promises and store in an array
const fetchPromises = urlsToFetch.map(url => fetch(url).then(response => response.json()));
// Use Promise.all() to handle all fetch promises
Promise.all(fetchPromises)
.then(responses => {
const responseData = responses.map(response => response);
})
.catch(error => console.error('Error fetching data:', error));

Example : In this example we will see how we can fetch arrays of URL like apis using Promise.all method in javascript.






const urlsToFetch = [
];
 
// Function to fetch all of the URLs in parallel
const fetchURLs = async (urls) => {
    try {
        const promises =
            urls.map(url => fetch(url));
 
        // Wait for all of the promises to resolve
        const responses =
            await Promise.all(promises);
 
        // Extract JSON data from responses
        const data = await
            Promise.all(responses.map(response => response.json()));
 
        return data}
    catch (error) {
        throw new Error(`Failed to fetch data: ${error}`)}}
 
fetchURLs(urlsToFetch)
    .then(data => {
        console.log('Fetched data:', data)})
    .catch(error => {
        console.error('Error fetching data:', error)});

Output:

Output

Example 2 : In this example we created array of URLs and then we applied map method on that array an in each iteration we are initiating an HTTP request and storing response into fetchPromises.




const urlsToFetch = [
];
 
const fetchPromises = urlsToFetch.map(url =>
    fetch(url)
        .then(response => response.json())
);
 
Promise.all(fetchPromises)
    .then(responses => {
        const responseData = responses.map(response => response);
        console.log('Fetched data:', responseData);
    })
    .catch(error => console.error('Error fetching data:', error));

Output:

Output


Article Tags :