Javascript Closures – Returning Object to Calling Function

I am using Cordova and Angular for a small webapp. Here is the implementation process:

  1. LogsModel is created
  2. queryLogs() is called
  3. getLogsArray() is called – at this point, even in the function definition, console.log(this.logs['0']) returns undefined. I do not understand why.

LogsModel.prototype.logs = {};

LogsModel.prototype.getLogsArray = function (){
    console.log(this.logs['0']);
    return this.logs;
};

LogsModel.prototype.queryLogs = function (){

    var self = this;

    function getFromDb (tx){
        tx.executeSql('SELECT * FROM DEMO',[],querySuccess,self.query_fail);
    }

    function querySuccess(tx,results){
        var len = results.rows.length;

        for(var i = 0; i < len; i++){

            var log = {
                verb: results.rows.item(i).verb
            };
            self.logs[i]= {
                verb: results.rows.item(i).verb
            };
        }
    }
    this.db = window.openDatabase("Database","1.0","Cordova Demo",200000);
    this.db.transaction(getFromDb,self.transaction_fail);
};

queryLogs is an asynchronous task. Call getLogsArray directly after starting the transaction and the array won't be populated yet.

Instead, use a callback which you invoke from the querySuccess function to continue processing (e.g. logging results).