繁体   English   中英

异步函数为另一个异步函数存储数据

[英]async function store data for another async function

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

这是我的班级

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);

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

GET https://us1.locationiq.com/v1/reverse.php?key=MY_Private_KEY&lat=undefined&lon=undefined&format=json 400
(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..');
    }
}

您可以接受函数作为参数

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM