Как я могу получить данные из API-запроса из метода then (), чтобы я мог обрабатывать данные вне функции? - PullRequest
1 голос
/ 10 января 2020

Как я могу получить данные из API-запроса из метода then (), чтобы я мог обрабатывать данные вне функции. Могу ли я сохранить данные в объекте состояния, например, и как это сделать.

// openweathermap async await api request
async function getData(){

try{
const url = `http://api.openweathermap.org/data/2.5/forecast? 
                     q=${city}&units=metric&appid=${key}`;
const data = await axios(url)

console.log(data)
        return data;
}catch(error){
    temperature.insertAdjacentHTML('afterend', '<div id="error">Oooops 
                                         something went wrong!</div>');

}

}
 getData().then( data => {

        const temp = data.data.list[0].main.temp;
        temperature.textContent =  temp.toFixed(1) + ' \xB0' + "C ";
        const temp2 = data.data.list[1].main.temp;
        temperature2.textContent =  temp2.toFixed(1) + ' \xB0' + "C ";

        const forecast = data.data.list[0].weather[0].description;
                       foreCast.textContent = forecast.toLowerCase();
        const forecast2 = data.data.list[1].weather[0].description;
                        foreCast2.textContent = forecast2.toLowerCase();

        const icon = data.data.list[0].weather[0].icon
                   weatherIcon.insertAdjacentHTML('afterbegin', `<img 
                   src="http://openweathermap.org/img/w/${icon}.png">`) 
        const icon2 = data.data.list[1].weather[0].icon
                   weatherIcon2.insertAdjacentHTML('afterbegin', `<img 
                   src="http://openweathermap.org/img/w/${icon2}.png">`) 

                    day.textContent = newTime;
                   day2.textContent = newTime2;

       })

Ответы [ 3 ]

2 голосов
/ 10 января 2020

Если axios(url) должно быть axios.get(url)?

Тогда вы можете обрабатывать данные внутри функции обратного вызова:

getData().then(data => console.log(data))
1 голос
/ 11 января 2020

Нашли решение: создайте класс с помощью метода getData (), создайте функцию для управления данными и сохраните их в объекте состояния.

// Create class
class Weather {
constructor(){   

}

async getData(){
try{
     const url = `http://api.openweathermap.org/data/2.5/forecast? 
                             q=${city}&units=metric&appid=${key}`;
     const data = await axios(url)

     this.data = data
 }catch(error){
        temperature.insertAdjacentHTML('afterend', '<div id="error">Oooops something 
                                                     went wrong!</div>');
        }

      }

   }


 // Create state object, declare function to get data and store data in state object

 const state = {}

 const controlData = async () => {

 state.data = new Weather()

          await state.data.getData()

 const temp = state.data.data.data.list[0].main.temp;
                     temperature.textContent =  temp.toFixed(1) + ' \xB0' + "C ";
 const temp2 = state.data.data.data.list[1].main.temp;
                     temperature2.textContent =  temp2.toFixed(1) + ' \xB0' + "C ";

 const forecast = state.data.data.data.list[0].weather[0].description;
                        foreCast.textContent = forecast.toLowerCase();
 const forecast2 = state.data.data.data.list[1].weather[0].description;
                         foreCast2.textContent = forecast2.toLowerCase();

 const icon = state.data.data.data.list[0].weather[0].icon
                    weatherIcon.insertAdjacentHTML('afterbegin', `<img 
                      src="http://openweathermap.org/img/w/${icon}.png">`) 
 const icon2 = state.data.data.data.list[1].weather[0].icon
                     weatherIcon2.insertAdjacentHTML('afterbegin', `<img 
                     src="http://openweathermap.org/img/w/${icon2}.png">`) 

                   day.textContent = newTime;
                  day2.textContent = newTime2;

 let sRise = convertTime(state.data.data.data.city.sunrise);
 let sSet = convertTime(state.data.data.data.city.sunset);
                  sunRise.textContent = `Sunrise ${sRise}`;
                   sunSet.textContent = `Sunset ${sSet}`;

}

controlData()
1 голос
/ 10 января 2020

Получить данные уже является асинхронной c функцией, которая означает, что она возвращает Обещание. Просто назначьте переменную data, вызвав функцию getData. Это должно быть сделано в функции asyn c.

(async () => {
    const data = await getData();

    const temp = data.data.list[0].main.temp;
    temperature.textContent =  temp.toFixed(1) + ' \xB0' + "C ";
    const temp2 = data.data.list[1].main.temp;
    temperature2.textContent =  temp2.toFixed(1) + ' \xB0' + "C ";

    const forecast = data.data.list[0].weather[0].description;
    foreCast.textContent = forecast.toLowerCase();
    const forecast2 = data.data.list[1].weather[0].description;
    foreCast2.textContent = forecast2.toLowerCase();

    const icon = data.data.list[0].weather[0].icon
    weatherIcon.insertAdjacentHTML('afterbegin', `<img src="http://openweathermap.org/img/w/${icon}.png">`) 
    const icon2 = data.data.list[1].weather[0].icon
    weatherIcon2.insertAdjacentHTML('afterbegin', `<img src="http://openweathermap.org/img/w/${icon2}.png">`) 

    day.textContent = newTime;
    day2.textContent = newTime2;
})();
...