Skip to content Skip to sidebar Skip to footer

Returning Array From Javascript Class Method To A Script

I'm building a javascript application using object oriented techniques and I'm running into a problem that I hope someone here can help me resolve. The following method is designed

Solution 1:

Cannot be done, if your function is calling an asynchronous function, the only way to return results is through a callback. That's the whole point of asynchronous functions, the rest of the code can keep going before the call is finished. It's a different way of thinking about returning values (without blocking the rest of your code).

So you'd have to change your code to the following (plus proper error handling)

retrieveAllStoreSearches : function(callback){
    this.db.transaction(
        function(transaction){
            transaction.executeSql(
                "SELECT name,store,address FROM searchResults ORDER BY name ASC",
                [],
                function(transaction, results){
                    var returnArr = [];
                    for(var i = 0; i < results.rows.length; i++){
                        var row = results.rows.item(i);
                        returnArr.push(row.name + ' | ' + row.address);
                    }
                    callback( returnArr );
                },
                this.errorHandler
            );
        }
    );
}

Then you can use console.log like the following

db.retrieveAllStoreSearches(function(records) {
    console.log(records ) 
});

Post a Comment for "Returning Array From Javascript Class Method To A Script"