0

我遇到了一些代码没有按预期执行的问题,我应该先解释一下它在做什么:

  • 在文档加载函数 selectForLists 正在查询一个包含足球比分的 sqlite DB,特别是一个名为 match 的表,然后调用函数 renderLists。

  • RenderLists 将播放团队放入一个已删除重复项的排序列表中。

  • 然后,对于此团队列表中的每个条目,调用 latestTest 函数,该函数从该团队正在比赛的比赛表中选择所有行并调用 latestTest2。

  • 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>');
}
4

2 回答 2

3

db.transaction和都是tx.executeSql异步函数,就像setTimeout, 如果你写

setTimeout(function(){
    doLater();
}, 1000)
doNow();

doNow()将在之前 doLater()执行,因为您创建的回调函数将在未来某个时间被调用。

在您的情况下,latestTest()调用db.transaction和然后tx.executeSql都是异步的。这意味着,回调函数latestTest2将在未来某个时间被调用,这将在被调用之后loaded()

于 2011-10-31T16:07:38.273 回答
2

该函数使用自己的回调latestTest调用另一个函数。回调将在 SQL 完成时执行,这将在任意时间执行。executeSQL

renderLists函数将继续正常执行(包括调用该loaded函数),除了与latestTests正在执行的回调有关的任何事情。

您的错误是认为loaded将“等待”执行 - 您仍然会有来自latestTest.

于 2011-10-31T15:59:51.370 回答