[英]Function not being called synchronously?
我遇到一些代碼未按預期執行的問題,我可能應該先解釋一下它在做什么:
在文檔加載功能中,selectForLists正在查詢包含足球得分的sqlite DB,特別是一個名為“ matchs”的表,然后調用renderenders函數。
RenderLists將比賽隊放入已刪除重復項的排序列表中。
然后,對於此球隊列表中的每個條目,都會調用最新測試功能,該功能會從比賽表中選擇該團隊正在比賽的所有行,並調用最新測試2。
LatestTest2會計算該團隊參加比賽的行數,並向插入的div輸出一些代碼。
對每個團隊而言,一旦完成該操作,就應該還原以完成renderLists函數並調用已加載的函數,除非它沒有這樣做,而且我必須增加調用此函數的延遲,因為它不會最后發生。
我希望有人可以告訴我這里出了什么問題,為什么在以上所有步驟完成后沒有調用加載的函數? 同樣,如果有人有任何技巧可以通過更有效的代碼實現相同的結果,我也非常希望。
抱歉,這篇文章很長,我敢肯定,很多人會發現代碼很糟糕,而且我知道這樣做的功能太多了,也許還有很多更好的方法,但是自從在uni中使用javascript以來已經有好幾年了,我一直在努力它和sqlite。
代碼位於下面或位於http://pastebin.com/7AxXzHNB,謝謝
function selectForLists() { //called on (document).ready
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM matches', [], renderLists);
});
}
function renderLists(tx, rs) {
var playingList = new Array();
for (var i = 0; i < rs.rows.length; i++) {
playingList.push(rs.rows.item(i)['playing']);
}
playingListSort = playingList.sort();
var playingListFinal = new Array();
playingListSort.forEach(function(value) {
if (playingListFinal.indexOf(value) == -1) {
playingListFinal.push(value);
}
});
for (var c = 0; c < playingListFinal.length; c++) {
latestTest(playingListFinal[c]);
}
loaded(); //not running last in the function
//setTimeout(loaded,1000);
/////Using a delay because it doesn't run after the above has completed
}
function latestTest(team) {
db.transaction(function(tx) {
tx.executeSql('SELECT * FROM matches WHERE playing="' + team + '"', [], latestTest2);
});
}
function latestTest2(tx, rs) {
counted = rs.rows.length;
var theFunction = rs.rows.item(0)['playing'];
$('#inserted').append('<li onclick="onToDate(\'' + theFunction + '\')"><img width="30px" height="25px" id="popupContactClose" src="style/soccer.png"><div id="popupContactClose2">' + counted + '</div></img>' + rs.rows.item(0)['playing'] + '</li>');
}
db.transaction
和tx.executeSql
都是異步函數,就像setTimeout
一樣,如果您編寫
setTimeout(function(){
doLater();
}, 1000)
doNow();
doNow()
將在 doLater()
之前執行,因為您創建的回調函數將在將來的某個時間調用。
在您的情況下, latestTest()
調用db.transaction
,然后調用tx.executeSql
,這兩者都是異步的。 這意味着,將在將來的某個時間調用回調函數latestTest2
,這將在調用loaded()
之后 。
latestTest
函數使用其自己的回調函數調用另一個executeSQL
函數。 SQL完成后將在任意時間執行該回調。
renderLists
函數將正常繼續執行(包括調用已loaded
函數),這與正在執行的latestTests
中的回調latestTests
。
您的錯誤是認為loaded
將“等待”被執行-您仍將有來自latestTest
數據庫代碼的掛起回調。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.