【发布时间】:2012-06-19 14:37:40
【问题描述】:
我试图在执行 AJAX 请求时伪造同步 JavaScript。
我有一个 getPagePath(id) 函数,它需要通过给它一个页面 ID 来获取页面的页面路径,它通过 Web API 接收数据。我认为这很简单,只需向服务器发出 ajax 请求并接收页面路径。但是发生了什么:当请求页面路径时,我的代码继续运行并返回一个空 var,之后 ajax 调用完成,但迟到了。
我知道我的解释不多,所以这是我的代码:
var getPagePath = function() {
// Function to check if this.pagePath is set.
var pagePathReady = function() {
console.log('PAGEPATH: CHECKING');
if (this.pagePath && this.pagePath != null) {
return true;
} else {
return false;
}
};
if (!pagePathReady()) {
// No pagePath defined so lets set it.
this._setPagePath();
while (!pagePathReady())
{
// Not yet defined, check again..
// *** The problem ***
// This while loop is running insanely fast making the browser crash.
// How can I make this wile loop pause for 1 sec?
// *******************
console.log('PAGEPATH: NOT READY -> CHECK AGAIN');
}
// READY
console.log('PAGEPATH: READY -> VALUE: ' + this.pagePath);
return this.pagePath;
} else {
return this.pagePath;
}
};
var _setPagePath = function() {
if (!this.pagePathRequestFired) {
this.pagePathRequestFired = true;
// Fire request.
system.url(
this.getNodeId(),
function(url) {
// Request ready, set pagePath.
this.pagePath = url;
this.pagePathRequestFired = false;
},
this
);
} else {
// Call already running..
}
};
我已将问题设置在更多解释的 cmets 中。
提前致谢!
【问题讨论】:
标签: javascript asynchronous timeout while-loop synchronous