javascript - 异步延迟 JS 直到满足条件

标签 javascript asynchronous google-closure-library

我有一个类 ChatRoom,它只能在收到长时间运行的 HTTP 请求(可能需要 1 秒或 30 秒)后呈现。所以我需要延迟渲染,直到 ChatRoom.json 不为空。

在下面的代码中,我使用了 Closure Library 的 goog.async.ConditionalDelay .它有效,但是否有更好的方法(也许不需要 Closure Library)来做到这一点?

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 执行)。

最佳答案

考虑一下:

(function wait() {
    if ( chatroom.json ) {
        chatroom.render();
    } else {
        setTimeout( wait, 500 );
    }
})();

这将每半秒检查一次。

现场演示: http://jsfiddle.net/kBgTx/

关于javascript - 异步延迟 JS 直到满足条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7559386/

相关文章:

javascript:去除输入字符串上的换行符

node.js - 等待异步方法完成

python - 在tensorflow的keras的fit_generator中,AsyncResult在意外情况下挂起

javascript - 有什么理由不在不同的源文件中提供相同的模块吗?

javascript - 使用 goog.events.listen 传递参数

php - 如何从另一个 php 页面更改一个页面的标签文本?

JavaScript 日期函数在 Firefox 中不起作用

javascript - Typescript + Jasmine/Mocha,但没有全局类型?

java - 如何在 Undertow 中的非阻塞处理程序中执行阻塞代码?

mootools - Mootools 和 Google Closure 库兼容吗?