反应本能的怀疑: Tryint 读取数据库并创建内容数组。在代码中,更新数组“rcpts”后,在尝试访问 db.transaction 块之外时它保持为空。如何真正更新该块内的数组?我问 bcz,即使在 db.transaction 块的 while 循环内更新后,数组似乎仍然为空或原始形式。
let rcpts = []
const db = SQLite.openDatabase('digit.db');
//date, agentNo, custName, custNo, paidAmount, custBalance, payMode, revGroup FROM tblRcpt ORDER BY Id DESC LIMIT 100
function pushreceipts(){
let rcptlist =[];
//Alert.alert("you clicked");
db.transaction(tx=>{
tx.executeSql("SELECT id,date, agentNo, custName, custNo, paidAmount, custBalance, payMode, revGroup FROM tblRcpt ORDER BY Id DESC LIMIT 100 ",
null,(tx,result)=>{
let len = result.rows.length;
if (len>0){
for(let i =0;i<len;i++){
let item = result.rows.item(i);
rcptlist.push({
rcptNo : item.id,
rcptdate : item.date,
agentNo : item.agentNo,
custName : item.custName,
custNo : item.custNo,
paidAmount : item.paidAmount,
custBalance : item.custBalance,
payMode : item.payMode,
revGroup : item.revGroup
});
i++;
}
}
rcpts = rcptlist;
Alert.alert("Data Push finished.")
//Alert.alert("Survey Added");
}),
(error) =>{
Alert.alert(error);
}
}
)
// **** Read the rcps Array and send using fetch here. ****
let qty = rcpts.length;
let i = 0;
console.log(rcpts.length)
while(i<qty+1){
console.log('length of rcpts array'+rcpts.length);
i++;
}
}
回答你的问题;
您正在发出回调,但尝试访问数组而不确保您的回调已被调用。你可以这样做:
const db = SQLite.openDatabase('digit.db');
//date, agentNo, custName, custNo, paidAmount, custBalance, payMode, revGroup FROM tblRcpt ORDER BY Id DESC LIMIT 100
function pushreceipts() {
let rcpts = new Promise((resolve, reject) =>
db.transaction(tx => {
tx.executeSql("SELECT id,date, agentNo, custName, custNo, paidAmount, custBalance, payMode, revGroup FROM tblRcpt ORDER BY Id DESC LIMIT 100 ",
null, (tx, result) => {
let len = result.rows.length;
let res = [];
if (len > 0) {
for (let i = 0; i < len; i++) {
let item = result.rows.item(i);
res.push({
rcptNo: item.id,
rcptdate: item.date,
agentNo: item.agentNo,
custName: item.custName,
custNo: item.custNo,
paidAmount: item.paidAmount,
custBalance: item.custBalance,
payMode: item.payMode,
revGroup: item.revGroup
});
i++;
}
}
resolve(res);
Alert.alert("Data Push finished.")
//Alert.alert("Survey Added");
}),
(error) => {
Alert.alert(error);
reject(error);
}
}))
// **** Read the rcps Array and send using fetch here. ****
let qty = rcpts.length;
let i = 0;
console.log(rcpts.length)
while (i < qty + 1) {
console.log('length of rcpts array' + rcpts.length);
i++;
}
}
但是,对于您想要做的事情来说,更合适的解决方案是使用Expo SQLite;
import * as SQLite from 'expo-sqlite';
const allRows = await db.getAllAsync("SELECT id,date, agentNo, custName, custNo, paidAmount, custBalance, payMode, revGroup FROM tblRcpt ORDER BY Id DESC LIMIT 100");
for (const row of allRows) {
console.log(row.id, row.value, row.intValue);
}