本文介绍了如何最佳地组合多个axios响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React应用程序.我必须使用来自3个不同API的响应来创建2个对象.例如:

I am working with a React app. I have to create 2 objects using responses from 3 different APIs. For example:

  1. 将使用API​​1和API2创建DataObject1
  2. 将使用API​​1,API2和API3创建DataObject2

因此,我正在考虑通过确保每个API仅调用一次一次来实现此目的的最佳方法.

So, I am thinking about what would be the most optimal way of doing this by making sure 1 call each API only once.

我当时在想:

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 }

有更好的方法吗?

推荐答案

看起来不错.

您可以更改

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

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

因为散布和休息是多余的.

because spreading and resting is redundant.

如果您不想使用它们,例如 responses [0] responses [1] 等,则可以使用:

If you don't want to use them like responses[0], responses[1], etc then you can use:

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

这篇关于如何最佳地组合多个axios响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 13:34