本文介绍了依次调用API,直到响应为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连续调用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循环无限期地继续,并且即使我知道第5页返回空值,该标志也永远不会设置为false.

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);

主要区别在于,发送一个请求后,此代码将不会发送另一个请求,直到响应返回并确认 length.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.

这篇关于依次调用API,直到响应为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 17:50