react-native-sqlite 值不显示
2021-01-21
65
this.getDetails();
getDetails = () => {
let userDetails = [];
db.transaction((tx) => {
tx.executeSql('select * from users where role=?',['students'],(tx,results) => {
let details = []
if(results.rows.length > 0){
for(let i=0; i < results.rows.length; i++){
details.push(results.rows.item(i));
}
}
userDetails = details;
//Data is displayed here
console.log(userDetails)
})
})
// Data is not printed here
console.log(userDetails) // []
}
在上面的代码片段中,我能够获取 tx.executeSql 内部的数据(userDetails),但不能获取 db.transaction 块外部的数据。
有人可以帮我解决如何在 db.transaction 块之外显示数据吗?
1个回答
定义一个 promise 函数,用于从 DB 获取
userDetails
。
async dbAction = () => {
return new Promise((resolve, reject) => {
db.transaction((tx) => {
tx.executeSql('select * from users where role=?',['students'],(tx,results) => {
let details = []
if(results.rows.length > 0){
for(let i=0; i < results.rows.length; i++){
details.push(results.rows.item(i));
}
}
//Data is displayed here
resolve(details);
})
})
});
}
然后你可以像这样调用它。
getDetails = () => {
let userDetails = [];
try {
let userDetails = await dbAction();
console.log(userDetails);
} catch (e) {
}
}
Honey
2021-01-21