如何通过抓取进行同步请求?

时间:2018-08-18 20:56:25

标签: javascript async-await fetch es6-promise

我正在使用纯JavaScript创建天气应用。我正在从某些api获取天气数据,我希望页面等待接收该数据,然后将检索到的数据加载到html中。我试图用Promise和async / await来做到这一点,但无法完成工作。

  

这是我的代码:

import getWeather from './getWeatherState';

const detailedForecast = () => {
    let city = document.querySelector('.weather-forecast__city');
    let date = document.querySelector('.weather-forecast__date');
    let currentDate = new Date();
    let weekDays = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
    let monthNames = ["January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December"]; 
    let celsius = document.querySelector('.weather-forecast__celsius');
    let description = document.querySelector('.weather-forecast__figcaption');
    let pressure = document.querySelector('.weather-forecast__pressure');
    let humidity = document.querySelector('.weather-forecast__humidity');
    let windSpeed = document.querySelector('.weather-forecast__wind-speed');
    let geocoder,latitude,longitude,currentCity;
    let detailedForecast = {

    }

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
        function geoSuccess(position) {
            let lat = position.coords.latitude;
            let lng = position.coords.longitude;
            getCurrentCity(lat,lng);
        }

        function geoError() {
            alert('Geocoder failed');
        }
        geocoder = new google.maps.Geocoder();

        function getCurrentCity(lat, lng) {
            let currentCity = new google.maps.LatLng(lat, lng);
            geocoder.geocode({'location': currentCity}, (results, status) => {
                if (status = google.maps.GeocoderStatus.OK) {
                    latitude = results[0].geometry.location.lat();
                    longitude = results[0].geometry.location.lng();
                    currentCity = results[0].address_components[4].short_name;

                    async function getData() {
                        await getWeather(currentCity, detailedForecast);
                        console.log(111);
                    }

                    getData();
                    console.log(detailedForecast, 'detailedForecast');
                    city.innerHTML = currentCity;
                    date.innerHTML = weekDays[currentDate.getDay()] + ', ' + monthNames[currentDate.getMonth()] + ' ' + currentDate.getDate() + ', ' + currentDate.getHours() + ':' + currentDate.getMinutes();
                    celsius.innerHTML = detailedForecast.currentTemp;
                    description.innerHTML = detailedForecast.weatherDescription;
                    pressure.innerHTML = detailedForecast.atmosphericPressure;
                    humidity.innerHTML = detailedForecast.humidity;
                    windSpeed.innerHTML = detailedForecast.windSpeed;
                }
            })
        }
    } else {
        alert('Geoloaction is not supported by this browser');
    }
}

export default detailedForecast;
  

这是进行抓取的函数:

export default (currentCity, detailedForecast) => {
    fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${currentCity},am&appid=bdb69b5685832284db539510d237124e`)
        .then(res => res.json())
        .catch(error => console.error('Error:', error))
        .then(res => {
            detailedForecast.currentTemp = res.list[0].main.temp - 273.15;
            detailedForecast.windSpeed = res.list[0].wind.speed;
            detailedForecast.weatherDescription = res.list[0].weather[0].description;
            detailedForecast.humidity = `${res.list[0].main.humidity}%`;
            detailedForecast.atmosphericPressure = `${res.list[0].main.pressure}mm Hg`;
            console.log(res, 'weather response');
    });
}

这是我的应用程序的序幕,我需要用未定义的数据加载页面。最后一个控制台位于fetch.then()

1 个答案:

答案 0 :(得分:1)

这种方法行不通,因为要在网页上设置值-您需要先呈现它,以便JS可以访问DOM并找到必要的元素。

如果您担心页面的外观,请考虑在数据出现之前使用某种loader来隐藏页面。

在getWeatherState处,您有一个获取请求,该请求仅会触发,但您的代码不会等待它,因为该函数不会返回任何promise。试试这个:

export default (currentCity, detailedForecast) => {
    return fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${currentCity},am&appid=bdb69b5685832284db539510d237124e`)
        .then(res => res.json())
        .catch(error => console.error('Error:', error))
        .then(res => {
            return {
                currentTemp: res.list[0].main.temp - 273.15,
                windSpeed: res.list[0].wind.speed,
                weatherDescription: res.list[0].weather[0].description,
                humidity: `${res.list[0].main.humidity}%`,
                atmosphericPressure: `${res.list[0].main.pressure}mm Hg`
            };
        });
}

然后,等待Promise返回main函数并assign返回结果:

getData().then(result=>{
    Object.assign(detailedForecast, result);
    console.log(detailedForecast, 'detailedForecast');
    ...
});