Javascript выборки API - PullRequest
       11

Javascript выборки API

0 голосов
/ 05 мая 2018

Я пытаюсь присвоить переменную стран ответу API выборки, но когда я распечатываю страны, я получаю undefined ? Кто-нибудь может объяснить мне, почему? и решение, если это возможно.

async function getCountries(url) {
    const data = await fetch(url);
    const response = await data.json();
    return response;
}

let countries;

document.addEventListener('DOMContentLoaded', () => {
    getCountries('https://restcountries.eu/rest/v2/all')
    .then(res => countries = res)
    .catch(err => console.log(err));

})

console.log(countries);

1 Ответ

0 голосов
/ 05 мая 2018
function getCountries(url) {
    return new Promise((resolve,reject)=>{
        fetch(url).then(res => {
            //You can parse the countries from the api response here and return to the 
            //event listener function from here using the resolve methood call parameter
            resolve(res);
        })
        .catch(err => console.log(err));
    })
}

document.addEventListener('DOMContentLoaded', () => {
    getCountries('https://restcountries.eu/rest/v2/all')
    .then(res => {
        //the returned value after api call and parsing will be available here in res
    })
})

Или, если вам не нужна другая функция для этой функции, вы можете получить ее напрямую следующим образом:

document.addEventListener('DOMContentLoaded', () => {
    let countries;
    fetch('https://restcountries.eu/rest/v2/all')
    .then(res => {
        //the returned value after api call and parsing out the countries hereit self
        countries = res.data.countries;
    })
})
...