簡體   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