Как переписать функцию с использованием Promise?

Начал учить async/await, на обычных задачках все выходит, решил написать pet проект, не выходит все связать воедино
Мне необходимо чтобы функция getCurrentWeather дождалась getCurrentPosition, и на основе её данных заполнила данные о широте и долготе

Так же у меня почему-то запросы к API вылетают сразу по 2 штуки

mounted() {
        this.getCurrentTime()
        this.getCurrentPosition()
        this.getCurrentWeather()
        setInterval(() => this.getCurrentWeather(), 2000)
    },


  methods: {
        getCurrentTime() {
            setInterval(() => {
                let currentDate = new Date()
                this.currentTime = [currentDate.getHours(), currentDate.getMinutes()].map(function (time) {
                    return time < 10 ? '0' + time : time
                }).join(":")
            }, 1000)

        },
        getCurrentWeather() {
                let ApiKey = 'КЛЮЧ'
                axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${this.lat}&lon=${this.long}&APPID=` + `${ApiKey}`)
                    .then(response => {
                        this.weather = response.data;
                        this.temp = response.data.main;
                        this.wind_speed = response.data.wind
                        this.sunrise = response.data.sys
                        this.sunset = response.data.sys
                    }).catch(error => {
                        console.log(new Error('Данные не получены, перезагрузите браузер'))
                    })

        },
        getCurrentPosition(){
            navigator.geolocation.getCurrentPosition(position => {
            this.lat = position.coords.latitude
            this.long = position.coords.longitude
        })
        },
  • Вопрос задан
  • 159 просмотров
Решения вопроса 1
polyak-888
@polyak-888
Js, React.js, css, frontend
Привет, вижу решение проблемы тремя способами:
1) getCurrentPosition будет таким
getCurrentPosition () {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(position => {
      resolve(position.coords)
    });
  })
}

а mounted таким
async mounted() {
        this.getCurrentTime()
        const coords = await this.getCurrentPosition()
        this.getCurrentWeather(coords)
        setInterval(() => this.getCurrentWeather(), 2000)
    },

если this.lat и this.long только нужны для вызова getCurrentWeather в mounted, то и незачем их класть в data
2) поставить watch this.lat и this.long и как только появится значение вызывать getCurrentWeather
3) Создать промис (new Promise) и resolve не вызывать сразу а поместить в переменную. Промис поместить в mounted, с await. А переменную с ссылкой на resolve вызвать в getCurrentPosition после того как получил координаты. Так как этот вариант не самый идеальный, код выкладывать не буду. Будет стимул поискать самому))
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы