0

I have a question regarding chaining promises and adding some additional data to be returned in the .then, along with carrying out another API request. I have seen a few similar posts but none that actually add additional data before firing off another api request where some variable needs to be dragged along through all promise results. Let me explain this with some code:

    axios.get(url1)
    .then(
        res1=>{
            return (
                res.data.somethingInteresting; // I need this result later
                axios.get(url2) // I need this to run and return before the next .then()
            )}
    )
    .then(res2=>{
        doSomething(res2);
    })

The api call to url2 depends on the api call to url1 having had taken place. The api call to url2 then takes place and returns a result. That result of the call to url2 is then used along with the result from the call to url1 in doSomething(). So res2 is a combination of the response from the call to url2 and the res.data.somethingInteresting, which came from the cal to url1.

Is it possible to ensure that the api call to url2 takes place but somehow grab hold of the results of the response from url1's call? I thought about setting the state but that would not work as that is an async call and therefore the state may not have updated by the time the subsequent function calls are executed.

1 Answers1

0

You can pass Promise.all to the next then for this purpose

return Promise.all([
  res.data.somethingInteresting,
  axios.get(url2)
])
Dmitry Reutov
  • 2,995
  • 1
  • 5
  • 20