依次调用 API 直到响应为空

2022-01-15 00:00:00 xmlhttprequest javascript

我正在尝试连续调用 API 并计数页面,直到响应为空.每个页面最多返回 1000 个结果",直到最终只返回 [].

I'm trying to call an API continuously and count through the pages until the response is empty. Each page returns a maximum of 1000 'results' until eventually returning only [].

我尝试过下面的代码,但 while 循环无限期地继续,并且标志永远不会设置为 false,尽管我知道第 5 页返回空.

I've had an attempt at the below code but the while loop continues indefinitely and the flag is never set to false, despite the fact that I know page 5 returns empty.

 var count = 1;
 var flag = true;
 var request = new XMLHttpRequest();

 while (flag == true) {
    request.open('GET', 'https://api.example.net/results/?page=' + count, true);
    count++;
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (data.length == 0) {
        flag = false;
      }
    }
    request.send();
 }

推荐答案

问题在于代码是异步.特别是,onload 回调仅在收到响应时触发,在调用之后的某个时间.您的脚本不会停止运行以等待"响应,因此它会继续遍历循环,因为 flag 仍然是 true.当空"响应出现并且 flag 变为 false 时,循环可能已经运行了数千次,从而设置了无用"的 Ajax 请求.

The problem comes from the fact that the code is asynchronous. In particular, the onload callback only fires when the response is received, some time after the call is made. Your script doesn't stop running to "wait" for the response, so it continues ploughing through the loop, because flag is still true. By the time an "empty" response comes and flag becomes false, the loop will have run potentially thousands of times, setting up "useless" Ajax requests.

@AmitJoki 已经建议了如何解决这个问题.这是一种方法(使用@PranavCBalan 建议的递归 - 尽管当我看到他的评论时我已经开始写这个了:-)):

@AmitJoki already suggested how to fix this. Here is one way to do it (using recursion as suggested by @PranavCBalan - although I had already started writing this when I saw his comment :-) ):

function sendRequest(count) {
    var request = new XMLHttpRequest();
    request.open('GET', 'https://api.example.net/results/?page=' + count, true);
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (data.length > 0) {
        sendRequest(count+1);
      }
    }
    request.send();
}

sendRequest(1);

关键区别在于,在发送一个请求后,此代码不会发送另一个请求,直到响应返回并确认 data.length 大于 0.

The key difference is that, after sending one request, this code won't send another one until the response is back and confirmed to have data.length greater than 0.

相关文章