van
van

Reputation: 27

How to call api parallelly in react using axios

I've list of Id's in an array, so I would like to pass each id to api end point, to get that particular id's information, so I want to do this in a parallel way instead of one by one call, So I'm using axios and also if there is a 1000 id's as batch I want to call 100 id's parallely, and again rest 100 id's, Can anyone suggest me the solution for this approach.

Here is the code:

  const getApiResponse=(gitIds)=>{
         let responseArray=[];
         return listOfIds?.map((listId)=>{

            const fetcServiceData = async (): Promise<void> => {
              return api.get(`api-end-point/${listId}`);
            }; 
            fetcServiceData()
            .then((value:any) => {
                const  response={
                    studentName: value.name,
                    grade: value.grade,
                }
                responseArray=[...responseArray,response]
               return responseArray
            })
            .catch((error)=>{
                console.log(error)
              })
          return responseArray;
        })
 
  }  

Upvotes: 0

Views: 837

Answers (3)

Schuere
Schuere

Reputation: 1639

Promise
  .all(/* list of async calls */)
  .then(doSomethingWithTheResults) 

will do what you want.

However, in the unlikely event that you are actually doing this, you should ask yourself the question, why am I clogging up my request line?

Say I'm asking for 10k records...

asynchronously...

to my server...

and 10 users do the same...

Won't that take an awful long time? Am I doing a hidden DDoS attack with my own code?

A more preferred way to counter this problem is to add an API endpoint in which you can give an amount of ids that return you the data you need.

const fetchServiceData = async (listIds: string[]): Promise<ListItem[]> => {
  return api.get(`api-end-point?listids=${listIds.join(',')}`);
}; 

Upvotes: 0

Laxman Sharma
Laxman Sharma

Reputation: 130

You should be able to create multiple promises and push them in an array and use Promise.all to resolve all of them together.

Keep in mind that Promise.all rejects as soon as any of those promises is rejected with the first error message.

Example:

const promise1 = fetchServiceData();
const promise2 = fetchServiceData();

Promise.all([promise1, promise2]).then(response => {
    const promise1Response = response[0];
    const promise2Response = response[1];

    // Do something with these responses.

}).catch(err => {
    // Do something with the error
});

Upvotes: 2

1harshh
1harshh

Reputation: 41

I like this pattern of chaining promises, returning them to keep the promise chain alive.

Like this:

axios
  .get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p1)
  .then(response => {
    this.setState({ p1Location: response.data });
    return axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p2);
  })
  .then(response => {
    this.setState({ p2Location: response.data });
    return axios.get('https://maps.googleapis.com/maps/api/geocode/json?&address=' + this.props.p3);
  })
  .then(response => {
    this.setState({ p3Location: response.data });
  }).catch(error => console.log(error.response));

Upvotes: 1

Related Questions