刷新后Javascript没有按顺序运行

时间:2014-03-20 19:44:03

标签: javascript asp.net-mvc-4

我有一个系统,用于通过检查用户是否已登录来标记读/未读消息,抓取匹配的用户药物条目,然后使用它。从视图到视图时它工作正常,但有时当我刷新时,它将首先运行显示代码(具有null dateLastSeen),然后运行从数据库中获取信息的代码(通过调试检查)。下面是代码在视图中的顺序:

<script type="text/javascript">
    // If user isn't logged in, hide submission/ignore drug visits
    // Otherwise, continue to else statement and figure out drug visit stuff
    var userLoggedIn = @Html.Raw(Json.Encode(ViewData["Username"])) + '';
    var dateLastSeen = null;
    if (userLoggedIn == "Guest") {
        $('.expandMessagePost').hide();
    }
    // If they're logged in but no pairing of user/NDC exists, set all messages to unread
    // If they're logged in and have visited the page, compare the date in the DrugVisit entry
    // and compare that to the message dates, and if they're newer, set them to unread
    else {
        $.getJSON("/api/DrugVisit", function (drugVisitsJsonPayload) {
            $(drugVisitsJsonPayload).each(function (i, item) {
                // Page has been visited
                if (item.NDC == '@Model.Item1.NDC' && item.Username == userLoggedIn) {
                    dateLastSeen = item.Date;
                    console.log("Date found!");
                }
            });
        });
    }

    $.getJSON("/api/Message/", function (messagesJsonPayload) {
        $(messagesJsonPayload).each(function (i, item) {
            if (item.NDC == '@Model.Item1.NDC') {
                var badge = "";
                // Check (if user logged in) if unread, update DrugVisit entry
                if (userLoggedIn != "Guest") {
                    if (dateLastSeen != null) {
                        if (item.Date > dateLastSeen) {
                            badge = "[UNREAD] - ";
                            console.log(dateLastSeen + " - " + item.Date);
                        }
                    }
                    else {
                        badge = "[UNREAD] - ";
                        console.log(dateLastSeen + " - " + "NULL WTF");
                    }
                }
                $("#messageListing").append('<li> \
                                            ' + badge + item.User + ' - ' + formatDateForOutput(item.Date) + ' - ' + item.Text + ' \
                                             </li>');
            }
        }
        );
    }
    );
</script>

这是某种竞争条件吗?我还是MVC和ASP.net的新手,所以我不知道该怎么做。谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

我不太清楚你希望事情发生的顺序,但你可能应该使用getJson调用中的.complete函数 - 例如,如果你想做{{1}然后,一旦你有了数据,做$.getJSON("/api/DrugVisit",你应该做类似的事情:

$.getJSON("/api/Message/"