我有一个类,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 执行)。