未显示 react-native-sqlite 值
react-native-sqllite value not displayed
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 块外的数据(userDetails)。
谁能帮我看看如何在 db.transaction 块之外显示数据。
定义一个从 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) {
}
}
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 块外的数据(userDetails)。
谁能帮我看看如何在 db.transaction 块之外显示数据。
定义一个从 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) {
}
}