Javascript 我想要一个回调函数内部的结果,另一个回调函数内部的结果

Javascript 我想要一个回调函数内部的结果,另一个回调函数内部的结果,javascript,cordova,web-sql,Javascript,Cordova,Web Sql,我在乞求javascript。我认为这个问题只涉及javascript,但它涉及PhoneGap和WebSQL。我的问题和我想做的都在代码注释中 var MyDatabase = function() { if (!(this instanceof MyDatabase)) return new MyDatabase(); } MyDatabase.prototype = { db: window.openDatabase("my_database", "1.0", "My D

我在乞求javascript。我认为这个问题只涉及javascript,但它涉及PhoneGap和WebSQL。我的问题和我想做的都在代码注释中

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();
有什么想法吗


谢谢。

您必须使用回拨。您不能在代码中返回
result
,因为尚未调用
onSuccess
,因此不会设置
result