我在表 parents_relations 中有一些数据。我试图在一个数组(arrayCollect)中填充所有 id 都在树结构内。
我的主要问题是如何在所有事件查询完成后触发 endd() 函数。
Deferreds有可能吗?
桌子
persons table
persons_id | Name
---------------------
1 | Name1
2 | Name2
3 | Name3
4 | Name4
5 | Name5
6 | Name6
7 | Name7
8 | Name8
9 | Name9
10 | Name10
11 | Name11
12 | Name12
13 | Name13
14 | Name14
15 | Name15
parents_relations table
p_r_id | contacts_id | parent_contacts_id
-----------------------------------------
1 | 11 | 3
2 | 11 | 4
3 | 3 | 1
4 | 3 | 2
5 | 9 | 3
6 | 9 | 4
7 | 8 | 1
8 | 8 | 2
9 | 5 | 1
10 | 5 | 2
11 | 4 | 14
12 | 4 | 15
推迟开始
var startItem = {
p_r_id: '',
contacts_id: '',
parent_contacts_id: '11'
};
var arrayCollect = [];
var temp = [];
temp.push(startItem);
$.when(builder(temp))
.done(function(dt){
endd();
console.log(arrayCollect);
});
这是递归函数
builder = function ( items) {
var deferB = $.Deferred();
deferArr.push(deferB);
if (items.length > 0) {
$.each(items, function (index, persn) {
arrayCollect.push(persn);
$.when(sqlGet_Parents(persn.parent_contacts_id, li)
).done(function(ret) {
deferB.resolve(ret);
builder(ret)
}).fail(function(){
alert("$.when(html5db.webdb.sqlGet_Parents.... failed!");
});
});
} else {
deferB.resolve();
}
return deferB.promise();
}
这是查询功能
sqlGet_Parents = function(idd) {
var deferB = $.Deferred();
var selectOk = function (transaction, results) {
var arrids = [];
for (var i = 0; i < results.rows.length; i++) {
arrids.push(results.rows.item(i));
}
deferB.resolve(arrids);
},
selectFail = function() {
var arrr = [];
deferB.reject(arrr);
};
var db = html5db.webdb.db;
db.transaction(function(tx){
tx.executeSql('SELECT * from parents_relations WHERE contacts_id = ? ',
[idd],
selectOk,
selectFail
);
});
return deferB.promise();
}
function endd(){
console.log(arrayCollect);
alert('Finaly!!!');
}