Fetch API requesting multiple get requests

后端 未结 4 1230
抹茶落季
抹茶落季 2020-12-07 18:18

I would like to know how to fetch multiple GET URLs at once and then put the fetched JSON data into my React DOM element.

Here is my code:



        
4条回答
  •  旧巷少年郎
    2020-12-07 18:27

    Here is how i fetched multiple endpoints as an example which may help someone

     const findAnyName = async() => {
    const urls = ['https://randomuser.me/api/', 'https://randomuser.me/api/'];
      try{
        let res = await Promise.all(urls.map(e => fetch(e)))
        let resJson = await Promise.all(res.map(e => e.json()))
        resJson = resJson.map(e => e.results[0].name.first)
        console.log(resJson)
      }catch(err) {
        console.log(err)
      }
    }
    findAnyName()
    

    Here is a complete example you can check on JSFiddle

    Or try this: declare all your URLs as an array. we will loop through this array and refer to single URL as array index.

         constructor(props) {
            super(props);
            this.state = { World: [], Afghanistan: [], USA: [], Australia: [] };
        }                                                                           
                           
     const urls = [
                'https://corona.lmao.ninja/v2/all',
                'https://corona.lmao.ninja/v2/countries/afghanistan',
                'https://corona.lmao.ninja/v2/countries/usa',
                'https://corona.lmao.ninja/v2/countries/australia'
            ];
        
        Promise.all(urls.map(url =>
                    fetch(url)
                        .then(checkStatus)  // check the response of our APIs
                        .then(parseJSON)    // parse it to Json
                        .catch(error => console.log('There was a problem!', error))
                ))
                    .then(data => {
                        // assign to requested URL as define in array with array index.
                        const data_world = data[0];
                        const data_af = data[1];
                        const data_usa = data[2];
                        const data_aus = data[3];
                        this.setState({
                                    World: data_world,
                                    Afghanistan: data_af,
                                    USA: data_usa,
                                    Australia: data_aus
                                })
                    })
       function checkStatus(response) {
                if (response.ok) {
                    return Promise.resolve(response);
                } else {
                    return Promise.reject(new Error(response.statusText));
                }
            }
    
        function parseJSON(response) {
            return response.json();
        }
    

    Result

    const { World, Afghanistan, USA, Australia} = this.state;
    
            console.log(World, Afghanistan, USA, Australia)
    

提交回复
热议问题