Home > database >  How to manage multiple async API calls in react
How to manage multiple async API calls in react

Time:10-12

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.

CodePudding user response:

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 }

CodePudding user response:

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);        
            });
        }

CodePudding user response:

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.

CodePudding user response:

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..
});
  • Related