-1

I'm using AWS amplify to make API calls, and i have 5 async API calls i need to make. How can I make these calls efficiently and wait for all of them to complete and than start work process with the data I got as a result of these calls.

Tibo
  • 621
  • 1
  • 8
  • 24
  • 1
    https://stackoverflow.com/questions/42158853/how-run-async-await-in-parallel-in-javascript/42158854#42158854 If you don't actually need the result of all the calls to make progress it may be better to launch them at the same time but awaiting them individually. – nlta Oct 12 '21 at 05:58
  • 1
    `Promise.all([ process1, process2, ...])` might come in handy. You can look for documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all) – Deep Patel Oct 12 '21 at 06:04

4 Answers4

3

Well actually I found out so here it is...

        load1 = async () => {
    
            return API.get('myApi', '/myapi1', {})
        }
    
        load2 = async () => {
    
            return API.get('myApi', '/myapi2', {})
        }
    
        verifyTasksExecution = async () => {
    
    
            Promise.all([this.load1(),this.load2()]).then((values) => {
    
                console.log('VALUES:', values);        
            });
        }
Tibo
  • 621
  • 1
  • 8
  • 24
1

to wait for multiple promises and wait for all of them to resolve you can use Promise.all which accepts an array of promises and returns an array of resolved data

you can read more about this in MDN, the following example is from MDN

// this will be counted as if the iterable passed is empty, so it gets fulfilled
var p = Promise.all([1,2,3]);
// this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled
var p2 = Promise.all([1,2,3, Promise.resolve(444)]);
// this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected
var p3 = Promise.all([1,2,3, Promise.reject(555)]);

// using setTimeout we can execute code after the stack is empty
setTimeout(function() {
    console.log(p);
    console.log(p2);
    console.log(p3);
});

// logs
// Promise { <state>: "fulfilled", <value>: Array[3] }
// Promise { <state>: "fulfilled", <value>: Array[4] }
// Promise { <state>: "rejected", <reason>: 555 }
Omid
  • 438
  • 4
  • 11
1

Assuming you're using JavaScript it sound like what you need is Promise.all()

call1 = axios(/* api request */)
call2 = axios()
call3 = axios()
call4 = axios()
call5 = axios()

Promise.all(call1, call2, call3, call4, call5).then(results => {
  // Do work here
  call1Result = results[0]
  call2Result = results[1]
  etc..
});
1

You could use promise.all to make all requests asynchronously. See this question for more details

Take note also that if any of the request fails, then promise.all rejects.

Paul Obike
  • 26
  • 3