[英]Node.js - http request is not working when inside a while loop
我正在使用unirest庫從api獲取所有數據,該api由offset和limits參數拆分,並且沒有有限數量的結果。
我正在使用一會兒條件來遍歷數據,在沒有返回結果的時候,我通過將“不完整”變量設置為false來結束循環。
但是由於某種原因,當我運行以下代碼時,直到得到'call_and_retry_last allocation failed'
錯誤為止,都不會發生任何事情(因為沒有向數據庫中添加任何數據,也沒有任何內容輸出到控制台)(假定在while循環進行時會發生這種情況)時間太長)。 但是,當我完全刪除while條件時,代碼可以正常工作。
有什么特殊原因為什么不起作用?
這是我的代碼:
var limit = 50,
offset = 0,
incomplete = true;
while (incomplete) {
// make api call
unirest.get("https://www.theapiurl.com")
.header("Accept", "application/json")
.send({ "limit": limit, "offset": offset })
.end(function (result) {
// parse the json response
var data = JSON.parse(result.raw_body);
// if there is data
if( data .length > 0 )
{
// save the api data
// + increase the offset value for next set of data
offset += limit;
}
else
{
// if there is no data left, end loop
incomplete = false;
console.log("finished!");
}
});
}
您可以將遞歸函數用作
function getServerData(offset){
//Your api service with callback.if there is a data then call it again with the new offset.
}
function getServerData(1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.