skip to Main Content

I am trying to code multiple dependent fetch get requests. Here number fetch call is a variable and each new request has previous response dependency

i try below pseudocode code, just need to set finalResult var after last fetch call

var finalResult = null;

af = async () => {
     Promise.resolve() 
    .then(x => console.log("first then"))
    .then(x_FromPreviousResponse => console.log("second then"))
    .
    .
    . 
    .then(z_FromPreviousResponse => finalResult = z_FromPreviousResponse)
     Promise.resolve()
    
}

af()

kindly give me code example or pseudocode

2

Answers


  1. You can use the then method as shown in the example below to make a new fetch call based on the results of the previous call after the previous call has completed. See the example code below.

    var finalResult;
    
    fetch('url1')
      .then(response1 => response1.json())
      .then(data1 => {
        return fetch('url2/' + data1.example);
      })
      .then(response2 => response2.json())
      .then(data2 => {
        return fetch('url3/' + data2.example);
      })
      .then(response3 => response3.json())
      .then(data3 => {
        finalResult = data3.finalValue;
        console.log(finalResult);
      })
      .catch(error => {
        console.error(error);
      });
    
    Login or Signup to reply.
  2. To make multiple dependent fetch requests, using the async/await syntax, makes it easier(to read of course since it’s a syntactic sugar) to handle asynchronous code.

    async function fetchData() {
      try {
        // First request
        const response1 = await fetch("url1");
        const data1 = await response1.json();
        console.log("first then");
    
        // Second request, depends on data1
        const response2 = await fetch(`url2?data=${data1.someValue}`);
        const data2 = await response2.json();
        console.log("second then");
    
        // More requests can be added in a similar way
        // ...
    
        // Final request
        const responseN = await fetch(`urlN?data=${dataNMinusOne.someValue}`);
        const finalResult = await responseN.json();
    
        // Do something with the final result
        console.log(finalResult);
      } catch (error) {
        console.error("Error occurred:", error);
      }
    }
    
    fetchData();
    

    Below is the small working code of aforementioned pseudocode, which uses JSON placeholder API. The example:

    1. fetches a todo,
    2. then fetches the user associated with that todo, and
    3. finally fetches the posts made by that user.
    async function fetchData() {
      try {
        // First request
        const response1 = await fetch("https://jsonplaceholder.typicode.com/todos/1");
        const data1 = await response1.json();
        console.log("first then", data1);
    
        // Second request, depends on data1 (userId)
        const response2 = await fetch(`https://jsonplaceholder.typicode.com/users/${data1.userId}`);
        const data2 = await response2.json();
        console.log("second then", data2);
    
        // Third request, depends on data2 (user's id)
        const response3 = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${data2.id}`);
        const finalResult = await response3.json();
    
        // Do something with the final result
        console.log("final result", finalResult);
      } catch (error) {
        console.error("Error occurred:", error);
      }
    }
    
    fetchData();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search