简体   繁体   中英

async function store data for another async function

I have a small weather app that first get location from browser of the user and store the lat and lon in object of a class. mathod getAdress() call the api to transform the lat and lon values to address.

this is my class

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

this is the index.js file

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

The error is the method get address try to fetch the data and call api without waiting for lat and lon values. this is the error and values are undefined

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

Using async/await like this does nothing. There are no promises involved, so nothing to await. getCurrentPosition uses callbacks for doing its asynchronous work, so you will need to wrap it in a promise yourself

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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