0

i am trying to return a column values from database in an array,but it always returns empty array.

function Select(query, db) {
var result = new Array();
db.transaction(function(tx) {
    tx.executeSql(query, [], function(tx, rs) {
        var len = rs.rows.length;

        for (var i = 0; i < len; i++) {
            var row = rs.rows.item(i);
            result.push({latitude : row['latitude']});
        }
    });

});
return result;
}

I am sure that array is created just after for loop but returns empty at last.

2 Answers 2

4

You are using asynchronous functions. So, direct return will not work. You need to use callback.

function Select(query, db, callback) {
    var result = new Array();
    db.transaction(function(tx) {
        tx.executeSql(query, [], function(tx, rs) {
            var len = rs.rows.length;
            for (var i = 0; i < len; i++) {
                var row = rs.rows.item(i);
                result.push({latitude : row['latitude']});
            }
            callback(result);
        });
    });
}

Select(function(result) {
    // do something with the result
})
Sign up to request clarification or add additional context in comments.

3 Comments

so, how can i implement callback function?should i do all asynchronous operations like database access in callback?
Yep, you can't expect that you will get the result immediately. At some point your code may work, but that's only because you didn't use the result of the async operation. Sooner or later you will meet the same problem.
thanks Karsimir,it helped me a lot.I will use this frequently on my project
0

Based on your description, it sound like tx.executeSql is asynchronous. That being the case, your Select method should return a Promise (also called a Future), or otherwise push the result back to the caller.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.