問題描述
我正在嘗試連續(xù)調(diào)用 API 并計(jì)數(shù)頁(yè)面,直到響應(yīng)為空.每個(gè)頁(yè)面最多返回 1000 個(gè)結(jié)果",直到最終只返回 []
.
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 循環(huán)無限期地繼續(xù),并且標(biāo)志永遠(yuǎn)不會(huì)設(shè)置為 false,盡管我知道第 5 頁(yè)返回空.
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
回調(diào)僅在收到響應(yīng)時(shí)觸發(fā),在調(diào)用之后的某個(gè)時(shí)間.您的腳本不會(huì)停止運(yùn)行以等待"響應(yīng),因此它會(huì)繼續(xù)遍歷循環(huán),因?yàn)?flag
仍然是 true
.當(dāng)空"響應(yīng)出現(xiàn)并且 flag
變?yōu)?false 時(shí),循環(huán)可能已經(jīng)運(yùn)行了數(shù)千次,從而設(shè)置了無用"的 Ajax 請(qǐng)求.
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 已經(jīng)建議了如何解決這個(gè)問題.這是一種方法(使用@PranavCBalan 建議的遞歸 - 盡管當(dāng)我看到他的評(píng)論時(shí)我已經(jīng)開始寫這個(gè)了:-)):
@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);
關(guān)鍵區(qū)別在于,在發(fā)送一個(gè)請(qǐng)求后,此代碼不會(huì)發(fā)送另一個(gè)請(qǐng)求,直到響應(yīng)返回并確認(rèn) 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.
這篇關(guān)于依次調(diào)用 API 直到響應(yīng)為空的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!