0

我正在尝试从 API 获取数据,但遇到了问题。该函数fetchCountryData无助于调试问题,因为它内部的任何断点都会被忽略。如何进入异步函数?

const [countryData, setCountryData] = React.useState([]);
const [borderCountries, setBorderCountries] = React.useState([]);

React.useEffect(() => {
    fetchCountryData();
}, [])

async function fetchCountryData() {
    /* fetch country by Name */
    const response = await 
        fetch(`https://restcountries.eu/rest/v2/name/${match.params.country}
               ?fields=${URL_FIELD_QUERIES}`);

    const fetchedData = await response.json();
        
    /* check if query by name returned multiple countries (the api unwillingly does that for some countries!) */
    let index = fetchedData.length === 1
                    ?   0   :   filterRequiredCountry(fetchedData, match.params.country);

    setCountryData(fetchedData[index]);

        
    /* .map() will run 'fetchNeighborName' function for each borders' item */
    const promises = fetchedData[index].borders.map(fetchNeighborName);

    /* the above promises will be resolved by Promise.all() */
    const neighborNames = await Promise.all(promises);

    setBorderCountries(neighborNames);
}

/* Extract 'alphaCode' for each bordered country and fetch its real name */

async function fetchNeighborName(alphaCode) {
    return fetch(`https://restcountries.eu/rest/v2/alpha/${alphaCode}?fields=name`)
        .then(response => response.json())
        .then(data => data.name);
}

function filterRequiredCountry(fetchedData, requiredCountry) {
    let requiredIndex;

    for (let index = 0; index < fetchedData.length; index++) {

        if (fetchedData[index].name === requiredCountry.toLowerCase()) {
            requiredIndex = index; break;
        }
    }
}
4

0 回答 0