如何使用axios在react中并行调用api

r1zk6ea1  于 2022-11-05  发布在  iOS
关注(0)|答案(3)|浏览(195)

我在一个数组中有一个ID列表,因此我想将每个ID传递给API端点,以获取特定ID的信息,因此我想以并行方式完成此操作,而不是逐个调用,因此我使用axios,并且如果有1000个ID作为批处理,我想并行调用100个ID,然后再调用其余100个ID,有谁能给我建议一下这种方法的解决方案吗?
下面是代码:

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

  }
yyyllmsg

yyyllmsg1#

您应该能够创建多个promise并将它们推入数组中,然后使用Promise.all一起解析所有这些promise。
Keep in mind that Promise.all rejects as soon as any of those promises is rejected with the first error message.
示例:

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

kgsdhlau2#

我喜欢这种连锁承诺的模式,返回它们以保持承诺链的活力。
就像这样:

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

yduiuuwa3#

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

我会做你想做的事。
然而,在不太可能的情况下,你实际上是这样做的,你应该问自己这个问题,为什么我堵塞了我的请求行?
假设我需要10k条记录...
异步...
到我的服务器...
10个用户做同样的事情...
这不是要花很长时间吗?我是不是在用自己的代码进行隐藏的DDoS攻击?
解决这个问题的一个更好的方法是添加一个API端点,在其中可以给予一定数量的id,这些id将返回所需的数据。

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

相关问题