我有一個類,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