[英]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.
mathod getAdress() 调用 api 将 lat 和 lon 值转换为 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这是 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);
The error is the method get address try to fetch the data and call api without waiting for lat and lon values.错误是方法 get address 尝试获取数据并调用 api 而不等待 lat 和 lon 值。 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.像这样使用 async/await 没有任何作用。 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
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.