如何等待AJAX​​请求完成在JavaScript时同步选项不可用?不可用、选项、AJAX、JavaScript

2023-09-11 01:33:03 作者:菊花朵朵开

我想等待AJAX​​请求完成。这将是容易,如果该方法 xmlhttp.open 将支持异步=假,但蚂蚁Galio不支持此选项,只有异步请求被允许。现在的问题是我怎么能等待回调被调用。

I'm trying to wait for the AJAX request to complete. It would be easy if the method xmlhttp.open would support async = false but Ant Galio does not support this option and only asynchronous requests are permitted. The question is how can I wait for the callback to be called.

    var ajaxFinished = false;
    var xmlhttp = new XMLHttpRequest();
    this.debug("-- onreadystatechange is being defined");
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            ajaxFinished = true;
                var data = xmlhttp.responseText;
            if (xmlhttp.status == 200) {
                that.debug('downloadSettings: SUCCESS');
                [...]
            } else {
                that.debug('downloadSettings:');
                that.debug('-- Error: ');
                that.debug('-- ResponseText: "'+data+'"')
            }
        }
    }

    while (ajaxFinished == false) {

    }

    this.debug("-- open connection");
    xmlhttp.open("GET", requestUrl, true); /* Ant Galio does not support synchronous  */
    this.debug("-- send");
    xmlhttp.send();                 

我在寻找某种积极的等待。我知道的另一种解决方案,但我感兴趣的是一个解决方案,不要求改变更多的code比我上面的例子。

I'm looking for some kind of active waiting. I know about another solution but I'm interested in a solution that would not require changing more of the code than is my example above.

谢谢!

推荐答案

您不能。有在JavaScript没有活性等待,只能有一个活动的执行时间(单线程)。

You can't. There is no "active waiting" in JavaScript, there can be only one active execution a time ("single-threaded").