【发布时间】:2011-09-26 18:16:52
【问题描述】:
我有一个类 ChatRoom,它只能在它接收到一个长时间运行的 HTTP 请求(可能需要 1 秒或 30 秒)后才能呈现。所以我需要延迟渲染,直到ChatRoom.json 不为空。
在下面的代码中,我使用了闭包库的goog.async.ConditionalDelay。它可以工作,但是有没有更好的方法(可能不需要闭包库)来做到这一点?
ChatRoom.prototype.json = null; // received after a long-running HTTP request.
ChatRoom.prototype.render = function() {
var thisChatRoom = this;
function onReady() {
console.log("Received JSON", thisChatRoom.json);
// Do rendering...
}
function onFailure() {
alert('Sorry, an error occurred. The chat room couldn\'t open');
}
function isReady() {
if (thisChatRoom.json != null) {
return true;
}
console.log("Waiting for chat room JSON...");
return false;
}
// If there is a JSON request in progress, wait until it completes.
if (isReady()) {
onReady();
} else {
var delay = new goog.async.ConditionalDelay(isReady);
delay.onSuccess = onReady;
delay.onFailure = onFailure;
delay.start(500, 5000);
}
}
请注意,“while (json == null) { }”是不可能的,因为那将是同步的(阻止所有其他 JS 执行)。
【问题讨论】:
-
为什么不使用来自 HTTP 请求的回调?
-
我无法使用该回调,因为可能会在 JSON 返回之前或在返回 10 分钟后调用 render。基本上,我希望能够在我想要的任何时间点调用 render()。
-
您仍然可以使用回调。在
render中,检查 JSON 是否已返回,如果没有,则添加到回调数组。或者只是使用 jQuery 的新 Deferred 对象,它会为你做这件事。
标签: javascript asynchronous google-closure-library