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;
}
JimmyShoe
  • 1,379
  • 10
  • 35
  • Check this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – FrV Aug 16 '19 at 08: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` – JimmyShoe Aug 16 '19 at 08:56
  • the referenced "duplicate" question is not directly applicable, IMHO. – Alnitak Aug 16 '19 at 08: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])`. – Alnitak Aug 16 '19 at 08: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? – JimmyShoe Aug 16 '19 at 09:12
  • `return Promise.all([p1, p2, p3]).then(() => items)` – Alnitak Aug 16 '19 at 09:26
  • or do `await Promise.all([p1, p2, p3]); return items` – Alnitak Aug 16 '19 at 09:27

1 Answers1

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;
}
Alnitak
  • 313,276
  • 69
  • 379
  • 466