【问题标题】:repeat function until true重复功能直到为真
【发布时间】:2012-11-20 12:49:23
【问题描述】:

我正在尝试调用一个 ajax 请求,直到它返回一个真值。我已经尝试了以下代码,但它没有返回任何结果,并且控制台中没有错误。知道我做错了什么吗?

function getUserData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    var resp = JSON.parse(xhr.responseText);
    return resp.status;
  }
}
xhr.send();
}

setInterval(function () {
if (getUserData() === "true") {
   alert("true");
}
}, 10000);

【问题讨论】:

  • 这将(尝试)每十秒发送一次 XHR,直到时间结束。
  • 你期待什么结果?

标签: javascript


【解决方案1】:

getUserData 在内部调用了一个异步函数,所以它在 AJAX 调用实际完成之前很久就返回了。

您可能想在失败的情况下再次尝试调用getUserData,而不是在 setInterval 循环中执行此操作。例如:

function getUserData() {
    var xhr = new XMLHttpRequest();

    xhr.open("GET", "http://api.example.com/data.json", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var resp = JSON.parse(xhr.responseText);
            if (resp.status) {
                alert("true");
            } else {
                setTimeout(getUserData, 10000);
            }
        }
    }
    xhr.send();
}

getUserData();

【讨论】:

  • 出现错误,未捕获 RangeError: 超出最大调用堆栈大小
【解决方案2】:

由于您将其称为异步,因此您无法从函数返回值。 试试这个:

function getUserData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    var resp = JSON.parse(xhr.responseText);
    if (resp === "true")
        alert("true");
    else
        getUserData();
  }
}
xhr.send();
}

【讨论】:

    【解决方案3】:

    是的,你的函数会立即返回,但总是返回 undefined。

    由于操作是异步的,您需要将其重写为基于回调。

    function getUserData(callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://api.example.com/data.json", true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState == 4) {
        var resp = JSON.parse(xhr.responseText);
        callback(resp.status);
      }
    }
    xhr.send();
    }
    
    setInterval(function () {
    var isTrue = "false";
    
    while(isTrue !== "true"){
       getUserData(function(result){ isTrue = result });
    }
    
    }, 10000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-24
      • 2013-12-28
      • 1970-01-01
      • 2021-08-19
      • 2021-07-13
      • 2011-08-25
      • 1970-01-01
      • 2021-05-22
      相关资源
      最近更新 更多