【问题标题】:Javascript synchronous timeout in while loopwhile循环中的Javascript同步超时
【发布时间】:2012-06-19 14:37:40
【问题描述】:

我试图在执行 AJAX 请求时伪造同步 JavaScript。 我有一个 getPagePath(id) 函数,它需要通过给它一个页面 ID 来获取页面的页面路径,它通过 Web API 接收数据。我认为这很简单,只需向服务器发出 ajax 请求并接收页面路径。但是发生了什么:当请求页面路径时,我的代码继续运行并返回一个空 var,之后 ajax 调用完成,但迟到了。

我知道我的解释不多,所以这是我的代码:

var getPagePath = function() {

    // Function to check if this.pagePath is set.
    var pagePathReady = function() {
        console.log('PAGEPATH: CHECKING');
        if (this.pagePath && this.pagePath != null) {
            return true;
        } else {
            return false;
        }
    };

    if (!pagePathReady()) {
        // No pagePath defined so lets set it.
        this._setPagePath();

        while (!pagePathReady())
        {
            // Not yet defined, check again..

            // *** The problem ***
            // This while loop is running insanely fast making the browser crash.
            // How can I make this wile loop pause for 1 sec?
            // *******************

            console.log('PAGEPATH: NOT READY -> CHECK AGAIN');
        }

        // READY
        console.log('PAGEPATH: READY -> VALUE: ' + this.pagePath);
        return this.pagePath;
    } else {
        return this.pagePath;
    }
};

var _setPagePath = function() {
    if (!this.pagePathRequestFired) {
        this.pagePathRequestFired = true;
        // Fire request.
        system.url(
            this.getNodeId(), 
            function(url) {
                // Request ready, set pagePath.
                this.pagePath = url;
                this.pagePathRequestFired = false;
            }, 
            this
        );
    } else {
        // Call already running..
    }
};

我已将问题设置在更多解释的 cmets 中。

提前致谢!

【问题讨论】:

    标签: javascript asynchronous timeout while-loop synchronous


    【解决方案1】:

    如果你真的需要,你可以同步 ajax 调用。

    xmlhttp.open("GET", "url", false);
    

    注意第三个参数。

    但是,我认为您只需要在编写代码以使用事件/回调概念时进行更多练习。

    【讨论】:

      【解决方案2】:

      为什么不轮询pagePath(恕我直言,这似乎不是必需的),为什么不在_setPagePath 准备好时执行回调?如果你想伪造一个同步请求,你可以只向用户显示一个加载微调器作为覆盖,禁用 UI。

      【讨论】:

      • 我使用这种方法是因为需要在另一段代码中设置pagePath,我将其设置为paramBag.path = this.controller.getPagePath();
      • 除了上面的评论:我使用这种方法是因为需要在另一段代码中设置pagePath,我将它设置为paramBag.path = this.controller.getPagePath();当使用回调时getPagePath()将在请求仍在运行时返回 undefined。当请求准备好时,它将调用回调,但回调无法设置 paramBag 中的属性。抱歉,我知道事情听起来不太清楚。很难解释这种情况..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 2014-07-06
      • 2021-11-18
      • 2017-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多