Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
How to return data from Promises if second fetch request depends on first?

I want to get some data from 2 apis, but i need some properties from the first api to make the fetch request to the second api. I also need the entire response from the first api.

export const fetchTrip = createAsyncThunk(
    'trip/fetchTrip',
    async (payload, thunkAPI) => {
        const result = fetch(
            'http://localhost:5000/user/trip/' + payload, {
            mode: 'cors',
            credentials: 'include',
            method: "get",
            headers: {
                'Content-Type': 'application/json'
            },
        })
        .then(response => response.json())

        .then(data => {
            const places= data.trips[0].places
            return Promise.all(places.map(place=>
                fetch('http://localhost:5000/api/tripadvisor/' + place.id)
                ))
                .then(resp => resp.json())
        })
        console.log(result)
        return result
    }
)

So the first fetch request will respond with some data such as

{
    title: "Cali Trip",
    budget: "1000",
    places: [
        {id: "123"}, 
        {id: "234"}, 
        {id: "345"}
    ]
}

I am using the place's id to fetch more details about that place. in the end, i want to return the trip detail from the first api, and all the details of the multiple places from the second api. I've tried the above code, but my response is undefined. ty in advance for any help!!

about 4 years ago · Santiago Gelvez
3 answers
Answer question

0

Since you are already making the function async, you could use await to make it more easy to follow, something along these lines, just a sketch for you to elaborate:

export const fetchTrip = createAsyncThunk(
  'trip/fetchTrip',
  async (payload, thunkAPI) => {
    const data = await fetch('http://localhost:5000/user/trip/' + payload, {
      mode: 'cors',
      credentials: 'include',
      method: 'get',
      headers: {
        'Content-Type': 'application/json',
      },
    }).then((resp) => resp.json());

    // here your first result
    console.log(data);

    const places = data.trips[0].places;
    const result = await Promise.all(
      places.map((place) =>
        fetch('http://localhost:5000/api/tripadvisor/' + place.id).then(
          (resp) => resp.json()
        )
      )
    );

    // here the second result
    console.log(result);

    // overwrite places with second result
    return {
      ...data,
      places: result,
    };
  }
);
about 4 years ago · Santiago Gelvez Report

0

This would be a lot cleaner if you didn't mix async / await with .then().

What you can do is return the response from the first request with the places array re-assigned with the values resolved from the secondary requests.

export const fetchTrip = createAsyncThunk(
  "trip/fetchTrip",
  async (payload, thunkAPI) => {
    const res = await fetch(
      `http://localhost:5000/user/trip/${encodeURIComponent(payload)}`,
      {
        credentials: "include", // cookies? Do you even need this?
      }
    );

    if (!res.ok) { // don't forget to check for failures
      throw res;
    }

    // pull out the first "trip" from the "trips" array
    const {
      trips: [{ places, ...trip }],
    } = await res.json();

    // respond with the "trip"
    return {
      ...trip,

      // resolve "places" by mapping the array to a new promise
      // and awaiting its result
      places: await Promise.all(
        places.map(async ({ id }) => {
          const placeRes = await fetch(
            `http://localhost:5000/api/tripadvisor/${encodeURIComponent(id)}`
          );
    
          // again, check for errors
          if (!placeRes.ok) {
            throw placeRes;
          }

          // resolve with the place data
          return placeRes.json();
        })
      ),
    };
  }
);
about 4 years ago · Santiago Gelvez Report

0

It seems you are mixing async/await code with Promise chaining code. While that's certainly valid, if we clean up your code a bit you can see that this is trivially done if you convert all of your code to async/await:

const response1 = await fetch('...');
const data1 = await response.json();
const data2 = await Promise.all([...]);

Of course, this can be done with Promise chaining by saving the data from inner calls into a variable outside the calls, but that's a far inferior option:

let data1;
let data2;

fetch('...')
  .then((response) => response.json())
  .then((data) => {
    data1 = data;
    
    return Promise.all([...]);
  })
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!