2012-05-23 22 views
0

我用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(); 

Any ideia?

謝謝。

回答

2

你必須使用回調。您的代碼中不能返回result,因爲onSuccess尚未被調用,所以沒有設置result

相關問題