skip to Main Content

How can I effectively manage multiple asynchronous data fetch requests in JavaScript using the Fetch API? I want to create an array of fetch requests, each returning a promise, and ensure that all results are processed before proceeding. What’s the best approach to achieve this while also handling potential errors in a clean way? Additionally, I would like to know how to handle timeouts and retries for the fetch requests.

o handle multiple asynchronous data fetch requests in JavaScript using the Fetch APi

2

Answers


  1. You can create multiple fetch request and call all fetch request using promise.all like

    promise.all([fr1, fr2,…])

    Login or Signup to reply.
  2. async function multiFetch() {
        const fetch1 = fetchWithErrorHandling("https://google.com", true);
        const fetch2 = fetchWithErrorHandling("/api/abcd");
    
        // Make sure all requests are completed before proceeding by using Promise.all
        const [fetch1Result, fetch2Result] = await Promise.all(
              [fetch1      , fetch2]);
    
        console.log(await fetch1Result.text());
    }
    
    async function fetchWithErrorHandling(url, tryUntilYouSucceed = false) {
        try {
            const fetchResult = await fetch(url);
            if(!fetchResult.ok) {
                // your choice if you would like to throw error or handle it like a boss.
                throw new Error("something went wrong boss! he's not ok.");
            }
            return fetchResult;
        }
        catch(e) {
            // handle your error!
            if(tryUntilYouSucceed) {
                return await fetchWithErrorHandling(url, true);
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search