gpt4 book ai didi

javascript - 是否可以在异步函数内将数据传递到它所在的类之外?

转载 作者:行者123 更新时间:2023-11-29 15:15:05 25 4
gpt4 key购买 nike

我正在使用 Ionic React 和 Capacitor 来尝试提取地理位置,然后尝试将其存储在数据库中。我试图将值存储在 App.coordinate 中,但每当我尝试将其导出到 map.ts 时,它都会将其以未定义的形式存储在数据库中。

是否有办法将地理位置数据从 getCurrentPosition() 函数传递到map.ts?

如您所见,我尝试了多种方法来尝试传递数据(如静态坐标/坐标!变量所示)。

应用程序.tsx

import * as React from 'react';
import { Plugins } from '@capacitor/core';
import { all } from '../server/db/maps';
const { Geolocation } = Plugins;

export class App extends React.Component<IAppProps, IAppState> {
state: any = {};
props: any = {};
lat!: number;
long!: number;
static coordinate: string;
coord!: string;

constructor(props: any) {
super(props);
this.state = { maps: [] };
this.getCurrentPosition();
}

async getCurrentPosition() {
const position = await Geolocation.getCurrentPosition();
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
this.coord = "[" + this.long + ", " + this.lat + "]";
App.coordinate = "[" + this.long + ", " + this.lat + "]";
console.log('Current', App.coordinate);
}

async componentDidMount() {
try {
let r = await fetch('/api/maps');
let maps = await r.json();
this.setState({ maps });
} catch (error) { console.log(error); }
}

render() {
return (
<main className="container my-5">
<h1 className="text-primary text-center">Geolocation</h1>
<ul className="list-group">
{this.state.maps.map(maps =>{ return <li className="list-group-item">{maps.id}, {maps.date}, {maps.coordinates} </li> })}
</ul>
</main>
);
}
}

export let Coordinates = App.coordinate; //App.coordinate passes on undefined
export interface IAppProps {}
export interface IAppState { maps: Array<{ id: string, date: Date, coordinates: string }>; }
export default App;

map .ts

import { Connection } from './index';
import { App, Coordinates } from '../../client/app';

export const all = async() => {
return new Promise((resolve, reject) => {
Connection.query('SELECT * FROM COORDINATES', (err, results) => {

if(err){
return reject(err);
}
resolve(results);
});

let stmt = 'INSERT INTO COORDINATES (id, date, coordinates) VALUES ? ';
let todos = [['3343', '2020-01-09 22:00:00', '[44.44444, 55.55555]'],
['5555', '2020-01-09 22:01:00', Coordinates]];
Connection.query(stmt, [todos], (err, results, fields) => {
if (err) {
return console.error(err.message);
}
// get inserted rows
console.log('Row inserted:' + results.affectedRows);
});
});
}

export default {
all
}

最佳答案

按照您尝试做的方式,不会工作

为什么?

因为您需要 App 类的实例来访问其“坐标”。即使您使用的是静态变量,该变量也只是动态填充,而不是静态填充。

如何解决?

您只能通过动态调用一个方法来存储坐标,并将插入逻辑与列表逻辑分开来解决这个问题。

看:

export const all = async() => (
new Promise((resolve, reject) =>
Connection.query('SELECT * FROM COORDINATES', (err, results) => {
if(err){
return reject(err);
}
resolve(results);
})
)

export const save = async (coordinates) => (
new Promise((resolve, reject) => {
// Make use of const variables as well
const stmt = 'INSERT INTO COORDINATES (id, date, coordinates) VALUES ? ';
const todos = [['3343', '2020-01-09 22:00:00', '[44.44444, 55.55555]'],
['5555', '2020-01-09 22:01:00', coordinates]]; // dynamic variable, not static.
Connection.query(stmt, [todos], (err, results, fields) => {
if (err) {
return console.error(err.message);
}
// get inserted rows
console.log('Row inserted:' + results.affectedRows);
});
});
)

然后,您可以从应用程序中调用它,最好是在 componentDidMount 上调用它(因为它是一个异步函数)

async componentDidMount() {
try {
let r = await fetch('/api/maps');
let maps = await r.json();
this.setState({ maps });
await this.getCurrentPosition()
// ... call to server to save this.coord
} catch (error) { console.log(error); }
}

async getCurrentPosition() {
const position = await Geolocation.getCurrentPosition();
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
this.coord = "[" + this.long + ", " + this.lat + "]";
console.log('this.coord', this.coord);
}

关于javascript - 是否可以在异步函数内将数据传递到它所在的类之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59743120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com