我使用全局变量来传递从AJAX调用中的响应。
window.response = null; // most recent response from XMLHttpRequest
// the callback function for XMLHttpRequest
function userObjFromJSON() {
if (this.readyState == 4) {
var json = eval( ( + this.responseText + ) );
window.response = json;
}
else {
indicateLoading();
}
}
// loads the info for this username on the page
function loadUsernameInfo(username) {
clearPage();
getUserInfo(username);
var profile = window.response; // most recent json response (what if it hasn t come in yet?)
window.response = null;
if (profile) {
indicateLoaded(username);
fillInProfileInfo(profile);
getTweets(username);
var tweets = window.response; // most recent json response (what if it hasn t come in yet?)
if (tweets) {
fillInTweets(tweets, MAX_TWEETS);
var mentions = mentionedUsers(tweets, MAX_TWEETS);
fillInMentioned(mentions);
}
else {
indicateUnavailableTweets();
}
}
else {
indicateInvalidUsername(username);
}
}
问题在于,当控制器函数想要开始填写信息时,AJAX调用有时还没返回。(如果我在调试器中缓慢步进,它就可以正常工作。)我该怎么做才能解决这个问题?
我试图这样做:
getUserInfo(username);
while (window.response == null); // infinite loop here
var profile = window.response; // most recent json response
但那只会让我的浏览器无响应。
我不太确定是否应该从回调函数中调用所需的函数,因为我正在尝试实现模型-视图-控制器。从模型中调用控制器/视图功能似乎会破坏模式。