我有一个类,ChatRoom
,它只能在接收到长时间运行的HTTP请求(可能需要1秒或30秒)后才能呈现。所以我需要延迟渲染,直到ChatRoom.json
不为空。异步延迟JS直到满足条件
在下面的代码中,我使用了Closure Library的goog.async.ConditionalDelay
。它可以工作,但有没有更好的方法(可能不需要Closure库)来做到这一点?
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请求的回调? – SLaks
我无法使用该回调,因为可能会在返回JSON之前或在返回10分钟之后调用render。基本上,我希望能够随时调用render()。 –
您仍然可以使用回调。在'render'中,检查JSON是否已经返回,如果没有,则添加到一个回调数组中。或者只是使用jQuery的新Deferred对象,它为你做到了这一点。 – SLaks