如何优化合并多个axios响应

odopli94  于 2022-11-05  发布在  iOS
关注(0)|答案(2)|浏览(138)

我正在使用一个React应用程序。我必须使用来自3个不同API的响应创建2个对象。例如:
1.将使用API1和API2创建DataObject1
1.将使用API1、API2和API3创建DataObject2
因此,我在考虑通过确保每个API只调用一次来实现这一点的最佳方式。
我在想:

const requestOne = axios.get(API1);
const requestTwo = axios.get(API2);
const requestThree = axios.get(API3);

axios.all([requestOne, requestTwo, requestThree]).then(axios.spread((...responses) => {
  const dataObject1 = createDataObject1(responses[0], responses[1]);
  const dataObject2 = createDataObject2(responses[0], responses[1], responses[2]);
  // use/access the results 
})).catch(errors => {
  // react on errors.
})

const createDataObject1 = (response1, response2) => { //Combine required data and return dataObject1 }
const createDataObject2 = (response1, response2, response3) => { //Combine required data and return dataObject2 }

有没有更好的方法?

wkftcu5l

wkftcu5l1#

看起来不错。
您可以更改此设置

axios.all([requestOne, requestTwo, requestThree]).then(axios.spread((...responses) => {
  const dataObject1 = createDataObject1(responses[0], responses[1]);
  const dataObject2 = createDataObject2(responses[0], responses[1], responses[2]);
  // use/access the results 
})).catch(errors => {
  // react on errors.
})

axios.all([requestOne, requestTwo, requestThree]).then((response) => {
  const dataObject1 = createDataObject1(responses[0], responses[1]);
  const dataObject2 = createDataObject2(responses[0], responses[1], responses[2]);
  // use/access the results 
}).catch(errors => {
  // react on errors.
})

因为它不需要伸展和休息。
如果你不想使用responses[0]responses[1]等,那么你可以用途:

axios.all([requestOne, requestTwo, requestThree]).then(axios.spread((response1, response2, response3) => {
  const dataObject1 = createDataObject1(response1, response2);
  const dataObject2 = createDataObject2(response1, response2,response3);
  // use/access the results 
})).catch(errors => {
  // react on errors.
})
vof42yt1

vof42yt12#

您是否使用thunk中间件在Redux中进行异步调用?我不想假设您是,但这似乎是一个很好的基本方法。

const requestOne = axios.get(API1);
const requestTwo = axios.get(API2);
const requestThree = axios.get(API3);

好了,现在requestOne.data有了axios get请求的结果,或者,如果thunk创建者是异步的,代码是const requestOne = await axios.get(API1);,会有结果吗
您是否需要进一步解析request___.data中的数据?
如果没有你可以

const dataObj1 = { response1: requestOne.data, response2: requestTwo.data }
const dataObj2 = { ... dataObject1, response3: requestThree.data };

满回答:

// store/yourFile.js code
export const YourThunkCreator = () => async dispatch => {
  try {
    const const requestOne = await axios.get(API1);
    // other axios requests
    const dataObj1 = { response1: requestOne.data, response2: requestTwo.data }
    const dataObj2 = { ... dataObject1, response3: requestThree.data };
    // other code
    dispatch(// to Redux Store);
  } catch (error) {
    console.error(error);
  }

相关问题