【问题标题】:async function store data for another async function异步函数存储另一个异步函数的数据
【发布时间】:2020-02-25 03:56:36
【问题描述】:

我有一个小型天气应用程序,它首先从用户的浏览器获取位置 并将 lat 和 lon 存储在类的对象中。 mathod getAdress() 调用 api 将 lat 和 lon 值转换为地址。

这是我的课

import axios from 'axios';
import { keyApp , keyMap , link} from '../config';

export default class Location {
   constructor(id){
      this.id = id;
 }
  async getLocation() {
    if(navigator.geolocation){
        (navigator.geolocation.getCurrentPosition(async position => {
            this.lat = await position.coords.latitude;
            this.lon = await position.coords.longitude;

        }));
    }
    else {
        console.log('Not able to get location..');
    }

}
async getAddress() {

     try {

        const address = await axios(`https://us1.locationiq.com/v1/reverse.php?key=${keyMap}&lat=${this.lat}&lon=${this.lon}&format=json`);

         this.address = address;
     }
     catch(e) {
         console.log(e);
     }
}

这是 index.js 文件

import Location from './modules/Location';
window.current = {}; //Testing purpose
const controlLocation = async () => {
  current.location = new Location(1);
  await current.location.getLocation();
  await current.location.getAddress();
  }

window.addEventListener('load' , controlLocation);

错误是方法获取地址尝试获取数据并调用 api 而不等待 lat 和 lon 值。 这是错误,值未定义

GET https://us1.locationiq.com/v1/reverse.php?key=MY_Private_KEY&lat=undefined&lon=undefined&format=json 400

【问题讨论】:

    标签: javascript async-await


    【解决方案1】:
    (navigator.geolocation.getCurrentPosition(async position => {
      this.lat = await position.coords.latitude;
      this.lon = await position.coords.longitude;
    }));
    

    像这样使用 async/await 没有任何作用。不涉及任何承诺,因此无需等待。 getCurrentPosition 使用回调来完成其异步工作,因此您需要自己将其包装在一个 Promise 中

    async getLocation() {
        if(navigator.geolocation){
            const position = await new Promise((resolve, reject) => {
              navigator.geolocation.getCurrentPosition(resolve, reject);
            });
            this.lat = position.coords.latitude;
            this.lon = position.coords.longitude;
        }
        else {
            console.log('Not able to get location..');
        }
    }
    

    【讨论】:

      【解决方案2】:

      你可以接受函数作为参数

      this.setState((position) => { lat: position.coords.latitude, lon: position.coords.longitude }

      【讨论】:

        猜你喜欢
        • 2021-04-14
        • 1970-01-01
        • 1970-01-01
        • 2019-09-26
        • 1970-01-01
        • 2021-08-07
        • 2017-07-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多