1

I currently have an async function that is similar to below. It returns an object which contains the results of several api calls(using axios - so each call returns a promise).

the problem i have is that the 3 api calls could be called at same time, but currently i am awaiting each one.

How would i be able to fire them all off at same time but still make sure the function only returns when all have finished. Do i need to put in a promise.all?

export async function GetItems(){
  let items ={
     items1:[],
     items2:[],
     items3:[]
  }

  await service.getItems1().then(r=>{
     items.items1 = r.data
  }

  await service.getItems2().then(r=>{
     items.items2 = r.data
  }

  await service.getItems3().then(r=>{
     items.items3 = r.data
  }

  return items;
}
7
  • Check this developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 16, 2019 at 8:56
  • thanks for marking this as a duplicate, i can see from the answer in that question that i do indeed need to use promise.all Commented Aug 16, 2019 at 8:56
  • the referenced "duplicate" question is not directly applicable, IMHO. Commented Aug 16, 2019 at 8:56
  • 1
    you do need to use Promise.all, but you don't then use await to call the three other functions, you do let p1 = service.getItems1( ... ), etc, and then return Promise.all([p1, p2, p3]). Commented Aug 16, 2019 at 8:57
  • @Alnitak how would i return my Items object? what would i do if i had an if statement around that last promise would that change things? Commented Aug 16, 2019 at 9:12

1 Answer 1

1

You need to get an individual Promise for each action, without using await, (thereby allowing them to run concurrently) and then use Promise.all to wait for all of them to complete:

export async function GetItems(){
  let items ={
     items1:[],
     items2:[],
     items3:[]
  }

  let p1 = service.getItems1().then(r=>{
     items.items1 = r.data
  }

  let p2 = service.getItems2().then(r=>{
     items.items2 = r.data
  }

  let p3 = service.getItems3().then(r=>{
     items.items3 = r.data
  }

  await Promise.all([p1, p2, p3]);

  return items;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.