更好的处理多个类似API调用的方式。

huangapple go评论71阅读模式
英文:

Better way to Handle multiple similar API calls

问题

我正在尝试使用React制作一个前端网站,并且正在使用NASA的API。我的主要问题涉及到4个火星探测器:好奇号(Curiosity)、机会号(Opportunity)、精神号(Spirit)和任务清单(Mission Manifest)。这些探测器都有与它们相关的API,可以提供它们拍摄的图片。我处理第一个探测器的方式如下:

//App.js
onTermSubmit = async (term) => {
        
        const response = await MarsPics_Curiosity.get('', {
            params: {
                earth_date: term,
                api_key: 'KEY'
        })
        
        this.setState({ Marspictures_Curiosity: response.data.photos, MarsDate_Curiosity: term })
        
    }

但后来我想要创建另外3个类似的函数来调用其他探测器的API。但是我意识到这似乎有些冗余和重复。所以,我想知道是否有更好的方法来处理这个问题,而不必创建另外3个单独的函数?

英文:

I am trying to make a front-end website using react, and I am using the APIs that NASA has. My main question pertains to the 4 Mars Rovers: Curiosity, Opportunity, Spirit, and Mission Manifest. Each of these Rovers have an API related to them that give out pictures that they have taken, and I handled the first Rover like this:

//App.js
onTermSubmit = async (term) =>{
        
        const response = await MarsPics_Curiosity.get('',{
            params:{
                earth_date: term,
                api_key: 'KEY'
        })
        
        this.setState({Marspictures_Curiosity: response.data.photos, MarsDate_Curiosity: term})
        
    }

And I was thinking of make 3 more of these to call the rest of the rover APIs. But then, I kind of realized that it seems kind of redundant and repetitive. So, I was wondering if there is a better way to handle this without making 3 more separate functions?

答案1

得分: 1

你可以将“rover”的名称传递给你的函数,然后根据这个参数计算字段和对象的名称。

async (term, roverName) => {
    const response = await window["MarsPics_" + roverName].get('', {
        params: {
            earth_date: term,
            api_key: 'KEY'
        }
    })

    this.setState({
        ["Marspictures_" + roverName]: response.data.photos,
        ["MarsDate_" + roverName]: term
    })

}
英文:

You can pass the name of rover into your function and calculate fields and objects names according this parameter

async (term, roverName) =>{
        const response = await window["MarsPics_" + roverName].get('',{
            params:{
                earth_date: term,
                api_key: 'KEY'
        })

        this.setState({
          ["Marspictures_" + roverName]: response.data.photos, 
          ["MarsDate_" + roverName]: term
        })

    }
    ```

</details>



# 答案2
**得分**: 1

在你的情况下,由于你不想一遍又一遍地编写函数,你可以将该函数定义为静态函数,将函数中的任何更改,如URL、参数,作为参数传递给函数。

```javascript
onFetchData = async (url, params) => {
    const response = await MarsPics_Curiosity.get(url, {
        ...params
    })

    this.setState({ Marspictures_Curiosity: response.data.photos, MarsDate_Curiosity: term })

}

然后调用该函数并传递所需的参数:

const resp1 = await onFetchData('/api1', { date: '2020-01-06' })
const resp2 = await onFetchData('/api2', { name: 'Mars' })

其中的一个优点是,你可以为每个调用检查错误并在出现错误时显示错误消息。

正如@Andus在评论中提到的,你也可以使用 Promise.all,但如果其中一个失败,那么所有操作都会失败。基本上,它会返回一个包含所有成功响应的数组,或者如果有一个失败,则会发送错误。你可以在这里上阅读更多信息。

希望这能帮助你更好地理解问题。

英文:

So in your case since you don't want to write again and again the function what you can do is make the function static and whatever changes in the function like url, params, pass it as params to the function

onFetchData = async (url,params) =&gt;{
        const response = await MarsPics_Curiosity.get(url,{
            ...params
        })

        this.setState({Marspictures_Curiosity: response.data.photos, MarsDate_Curiosity: term})

    }

And call the function as and pass the required params,

const resp1 = await onFetchData(&#39;/api1&#39;, {date: &#39;2020-01-06&#39;})
const resp2 = await onFetchData(&#39;/api2&#39;, {name: &#39;Mars&#39;})

One advantge on this basically you can have error for each one and show the error message if one fails

As @Andus mentioned in the comment you can use Promise.all, but if one fails everything gets failed. So basically it returns all the success response in an array or if one got failed it will send the error. You can read more on here

I hope this will get you better view of the problem

huangapple
  • 本文由 发表于 2020年1月6日 16:35:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定