我有一个系统,通过检查用户是否登录、抓取匹配的用户药物条目,然后使用它来将消息标记为已读/未读。从一个 View 切换到另一个 View 时它工作正常,但有时当我刷新时,它会首先运行显示代码(具有空 dateLastSeen),然后运行从数据库获取信息的代码(通过调试检查)。下面是按 View 中的顺序排列的代码:
<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 还很陌生,所以我不知道在这里做什么。感谢您的帮助。
最佳答案
我不太明白您希望事情发生的顺序,但您可能应该使用 getJson 调用中的 .complete
函数 - 例如,如果您想做 $.getJSON("/api/DrugVisit"
然后,一旦您获得了数据,就执行 $.getJSON("/api/Message/"
,您应该执行类似的操作:
$.getJSON("/api/DrugVisit", function (drugVisitsJsonPayload) {
//do stuff
}).complete(function() {
$.getJSON("/api/Message/", function (messagesJsonPayload) {
//do more stuff, knowing that the first call is finished
});
});
关于刷新后 JavaScript 未按顺序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22543506/