0

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 块之外显示数据。

4

1 回答 1

1

userDetails定义一个从 DB获取的 promise 函数。

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) {
     }
}
于 2021-01-21T10:25:00.217 回答