我正在尝试在 Phonegap (Cordova) 应用程序中显示项目列表,其中每个项目都需要额外的查询。
为简单起见,我将举例说明。假设 astudent
可以有多个course
s,acourse
可以有多个student
s(多对多),我想显示一个列表,显示学生注册了哪些课程。像这样:
- 学生 1:课程 1、课程 2
- 学生 2:课程 1、课程 3、课程 5
- 学生 3:课程 2
- ...
首先,我需要一个查询来遍历所有学生,然后对于每个学生,我需要查询数据库以了解学生注册了哪些课程:
db.transaction(function(tx) {
tx.executeSql('SELECT `student`.`id`, `student`.`name` ' +
'FROM `student`',
[],
function(tx, resultSet) {
for(var i = 0; i < resultSet.rows.length; i++) {
tx.executeSql('SELECT `course`.`name` ' +
'FROM `student_has_course` ' +
'INNER JOIN `student` ON `student_has_course`.`student_id` = `student`.`id` ' +
'INNER JOIN `course` ON `student_has_course`.`course_id` = `course`.`id` ' +
'WHERE `student`.`id` = ?'
[resultSet.rows.item(i).id],
function(tx2, resultSet2) {
// TODO
});
}
});
}, function(err) {
showError('Error getting students from the DB (' + err.message + ')');
}, function() {
alert('success!');
});
现在,问题是在第二个回调函数(“TODO”所在的位置)中,我没有引用前一个查询的任何数据。例如,如果我尝试alert(i)
它会警告 76,相当于resultSet.rows.length
. 这显然是因为这两个回调函数都是异步的。我怎样才能克服这个问题并打印如上所示的列表?
非常感谢任何帮助。