Return executeSQL function

2019-07-12 11:07发布

I'm trying to return the results of a SQL query using SQLite. The query works fine and I can output the results inside the executeSql function. But when I try to reach the array from my main function (returnSQLArray) it is undefined. How do I solve this problem?

I'm calling returnSQLArray inside another function where I need the results from the query.

Code:

function returnSQLArray(str) 
{
    var db = window.openDatabase("Database", "1.0", "Name", 200000);
    var result = [];
    db.transaction(
        function (tx, results) {
             tx.executeSql(str, [], function(tx, rs) {
                 for(var i=0; i<rs.rows.length; i++) {
                      var row = rs.rows.item(i)
                      result[i] = {
                          id: row['id']
                      }
                 }
                 console.log(result[0].id); //Returns the id
            });                   
        }
    );
    console.log(result[0].id); //Undefined     
}

Thank you

1条回答
疯言疯语
2楼-- · 2019-07-12 11:16

It's an async issue. db.transaction takes a callback which executes after the sqlite transaction finishes. Your console.log() statement shown at the end of your method is actually happening before result has been populated.

EDIT ADDITION:

functions getPersons() {
  returnSQLArray('SELECT * FROM PERSONS', processPersonsResponse); 
}

function returnSQLArray(str, callback) {
  ...
  tx.executeSql(str, [], function(tx, rs) { callback(result); });
}

function processPersonsResponse(response) {
  //do work with response
}
查看更多
登录 后发表回答