Javascript Can';无法从另一个文件返回数据
我正在使用一个外部实用程序文件。这只是一个JS文件Javascript Can';无法从另一个文件返回数据,javascript,react-native,async-await,Javascript,React Native,Async Await,我正在使用一个外部实用程序文件。这只是一个JS文件 export const getUser = async () => { db = SQLite.openDatabase("PegaPreco_data_src"); await db.transaction(tx => { tx.executeSql( "create table if not exists user (id text primary key not null, cpf text, n
export const getUser = async () => {
db = SQLite.openDatabase("PegaPreco_data_src");
await db.transaction(tx => {
tx.executeSql(
"create table if not exists user (id text primary key not null, cpf text, nome text, " +
"email text, senha text);"
);
});
return await db.transaction(tx => {
tx.executeSql("select * from user", [],
(_, { rows }) => {
console.log('My rowa', rows._array[0]); //console print - Ok
return rows._array[0];
},
(error) => {
console.error('Data errors \n', error);
})
})
}
在我的完整状态组件中,我导入了de实用程序文件,我正在尝试获取数据:
componentDidMount() {
getUser()
.then((MyUser) => {
console.log(MyUser); //undefined here
this.setState({ user: MyUser });
})
.then(console.log('My console.log for tests', this.state.user)); always the user is undefined
...more code...
我不知道怎么了。
初始状态为Ok,因为您实际上需要从getUser()返回数据。您可以使用promise resolve reject来实现这一点。我不熟悉您正在使用的库,但它看起来像是调用了
db.transaction
,然后tx.executeSql
不会返回任何内容,即它不是一个promise
以某种值进行解析/拒绝的库。它看起来是基于回调的,因此您必须“手动”执行该操作,并将其转换为承诺
这里有一个可能的解决方案:
//正在使用的'db'库的模拟
常量mockDb={
事务:回调=>{
回拨({
executeSql:(arg1、arg2、cb)=>{
const user={id:1,姓名:“John Doe”,年龄:20};
cb(空,用户);
}
});
}
};
//utils/getUser.js
const getUser=()=>{
返回新承诺((解决、拒绝)=>{
const db=mockDb;
数据库事务(tx=>{
tx.executeSql(“…”,“…”,()=>{});
});
数据库事务(tx=>{
tx.executeSql(“…”,[],(\ux,结果)=>{
决心(结果);
});
});
});
}
//组件/MyComponent.js
getUser()
.then(result=>{console.log('result',result);})
.catch(error=>{console.error(error);})
谢谢大家。
我已经重构了我的代码,我意识到这种方法是可行的
export const getUser = async () => {
db = SQLite.openDatabase("PegaPreco_data_src");
return new Promise((resolve, rejected) => {
db.transaction(tx => {
tx.executeSql("select * from user", [], (_, { rows }) => {
resolve(rows._array[0]);
});
});
})
}
但是,包含一个代码示例是一个好主意,不管它有多简单。标记为不确定你的意思?我包括了一个工作示例和解释-见下文。