2012-05-23 2 views
0

저는 javascript로 시작하고 있습니다. 나는 자바 스크립트에 대해서만이 질문을 생각하지만 그것은 PhoneGap과 WebSQL을 envolves. 내 문제와 내가하고 싶은 것은 코드 주석에있다.다른 콜백 함수의 내부에 콜백 함수가있는 결과가 필요합니다.

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

모든 ideia?

감사합니다.

답변

2

콜백을 사용해야합니다. onSuccess이 아직 호출되지 않았으므로 result을 코드에 반환 할 수 없으므로 아무 것도 result으로 설정되지 않습니다.