我想将SQLite数据库命令封装在'DBManager'类中。为了阅读数据,我写了以下几行:
DBManager.prototype.readMyData = function(param1, param2) {
this.db.transaction(function(tx) {
tx.executeSql("SELECT * FROM myTable WHERE param1 <= ?",
[param1],
function(tx, result) {
var myData = [];
for (var i=0; i<result.rows.length; i++) {
var row = result.rows.item(i);
myData.push(row);
}
},
errorHandler);
});
return myData;
}
问题:如果我调用方法readMyData(),则在事务方法及其内部函数之前执行return命令。
如何处理它以使readMyData()
的返回值不为空但保留myData
数组?
答案 0 :(得分:1)
你不能,你必须回复readMyData
:
DBManager.prototype.readMyData = function(param1, param2, callback) {
this.db.transaction(function(tx) {
tx.executeSql("SELECT * FROM myTable WHERE param1 <= ?", [param1],
function(tx, result) {
var myData = [];
for (var i=0; i<result.rows.length; i++) {
var row = result.rows.item(i);
myData.push(row);
}
callback(myData); // <- passing the data to the callback
},
errorHandler);
});
}
然后用:
调用它db.readMyData(foo, bar, function(result) {
// work with result here
});