0

Goal: Make 2 different get requests and use the data together from the two requests.

The Issue: I need to use the the data outside of .then({}) as I can use it for my purpose.

Following the simplified version of what im trying to do.

function main(){
  const data1 = getData(URL1).then((data) => {
      console.log(data) //I have access to data here
    }
 
 const data2 = getData(URL2).then((data) => {
      console.log(data) //I have access to data here
    }
  

   console.log(data1) // I get Promise { <pending> }
   console.log(data2) // Same as above

   <Do something with data1 and data2 here>

  }





  async function getData(url){
      let data = (await axios.get(url)).data
   }
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ASDFGerte Jul 23 '20 at 02:20
  • It has to happen inside of the function you pass to `.then`. You can have an instance of a previously declared higher scoped Object in the `.then` function, though. – StackSlave Jul 23 '20 at 02:21

2 Answers2

1
async function main(){
  const data1 = await getData(URL1);
 
 const data2 = await getData(URL2);
  

   console.log(data1)
   console.log(data2)

   <Do something with data1 and data2 here>

  }





  async function getData(url){
      return (await axios.get(url)).data
   }
lei li
  • 1,244
  • 1
  • 12
  • 35
  • This works but I don't understand why we have to make both functions async await. – Harry Singh Jul 23 '20 at 02:51
  • @HarrySingh `async` means the function will return a `Promise`, `await` means `xxx().then()` in a sync way. `await` will block the code and wait async function. – lei li Jul 23 '20 at 04:21
0
const data1 = getData(URL1);
const data2 = getData(URL2)

const data = Promise.all([data1, data2]).then(([result1, result2]) => {
   // do stuff
   // remember to return something or data won't equal anything
})

or if you are using async await

const data1 = getData(URL1);
const data2 = getData(URL2)

const [result1, result2] = await Promise.all([data1, data2]);
// do stuff
jDesign
  • 28
  • 5