为什么变量 len 值在数据库事务中没有改变?
Why variable len value not changing in db transaction?
//this is constructor of my code
constructor(props) {
super(props);
this.state = {
textValue:this.getFavoritesLength(),
};
}
//此 sqlite 代码 db.transaction 执行 prefect 但它不会更改 var len 的值它总是 returns 0 而我将 len 的值更改为 table 长度。
getFavoritesLength()
{
var len = 0;
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM table_favorites', [],
(tx, results) => {
len = results.rows.length;
console.log('select * results are = ', len);
// if (len > 0) {
// return len;
// }else{
// return 0;
// }
}
);
});
return len;
}
虽然 运行 查询它不会立即提供响应。查询的执行需要一些时间,并在回调函数中给出响应。
您可以尝试使用 async
insertarDatos = () => {
return new Promise((resolve, reject) => {
db.transaction((tx) => {
try {
/* Successful transaction */
/* Make sure to call resolve when the transaction has finished, maybe
db.transaction has a success callback
*/
resolve()
} catch (error) {
/* Failed transaction */
// if you reject any eventual errors, you can catch them when calling the function insertarDatos
reject(error)
}
});
})
}
//this is constructor of my code
constructor(props) {
super(props);
this.state = {
textValue:this.getFavoritesLength(),
};
}
//此 sqlite 代码 db.transaction 执行 prefect 但它不会更改 var len 的值它总是 returns 0 而我将 len 的值更改为 table 长度。
getFavoritesLength()
{
var len = 0;
db.transaction(tx => {
tx.executeSql(
'SELECT * FROM table_favorites', [],
(tx, results) => {
len = results.rows.length;
console.log('select * results are = ', len);
// if (len > 0) {
// return len;
// }else{
// return 0;
// }
}
);
});
return len;
}
虽然 运行 查询它不会立即提供响应。查询的执行需要一些时间,并在回调函数中给出响应。 您可以尝试使用 async
insertarDatos = () => {
return new Promise((resolve, reject) => {
db.transaction((tx) => {
try {
/* Successful transaction */
/* Make sure to call resolve when the transaction has finished, maybe
db.transaction has a success callback
*/
resolve()
} catch (error) {
/* Failed transaction */
// if you reject any eventual errors, you can catch them when calling the function insertarDatos
reject(error)
}
});
})
}