Home > Enterprise >  How to call api parallelly in react using axios
How to call api parallelly in react using axios

Time:10-12

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

CodePudding user response:

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

CodePudding user response:

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