Hugo Maia Vieira
Hugo Maia Vieira

Reputation: 125

I want some result that is inside of a callback function inside of another one

I'm beggining with javascript. I think this question only about javascript but it envolves PhoneGap and WebSQL. My problem and what I want to do are in the code comments.

var MyDatabase = function() {
    if (!(this instanceof MyDatabase)) return new MyDatabase();
}

MyDatabase.prototype = {
    db: window.openDatabase("my_database", "1.0", "My Database", 5000000),

    getAllPosts: function(callback) {
        var query = "SELECT * FROM posts",
            that = this,
            result;

        function onSuccess (transaction, resultSet) {
            console.log('get posts with success.');
            result = resultSet.rows; // I think this should work, but it doesn't
            if (typeof callback === 'function') callback.call(that, result);
        }

        function onError(transaction, error) {
            console.log(error);
        }

        this.db.transaction(function(t){ t.executeSql(query, [], onSuccess, onError) });

        return result; // result still undefined
    }
};

// Imagine that the posts table are created and has some rows seted.

var database = MyDatabase();

// The callback works fine.
database.getAllPosts(function(result) {
  // do something with result.
  console.log(result);
  // SQLResultSetRowList
});

// But in some cases I want to do this and I get result as undefined =(
var result = database.getAllPosts();

Any ideia?

Thanks.

Upvotes: 0

Views: 214

Answers (1)

Eric
Eric

Reputation: 97631

You have to use a callback. You can't return result in your code, since onSuccess won't yet have been called, so nothing will have set result.

Upvotes: 2

Related Questions