简体   繁体   English

Node.js-在while循环内时,http请求无法正常工作

[英]Node.js - http request is not working when inside a while loop

I'm using the unirest library to fetch all of the data from an api, which is split up by offset and limits parameters, and has no finite number of results. 我正在使用unirest库从api获取所有数据,该api由offset和limits参数拆分,并且没有有限数量的结果。

I'm using a while condition to iterate through the data and at the point where no results are returned, I end the loop by setting an 'incomplete' variable to false. 我正在使用一会儿条件来遍历数据,在没有返回结果的时候,我通过将“不完整”变量设置为false来结束循环。

But for some reason, when I run the following code nothing happens (as in no data is added to my database and nothing is outputted to the console) until I get the 'call_and_retry_last allocation failed' error (assuming this happens when a while loop goes on too long). 但是由于某种原因,当我运行以下代码时,直到得到'call_and_retry_last allocation failed'错误为止,都不会发生任何事情(因为没有向数据库中添加任何数据,也没有任何内容输出到控制台)(假定在while循环进行时会发生这种情况)时间太长)。 But when I remove the while condition altogether the code works fine. 但是,当我完全删除while条件时,代码可以正常工作。

Is there a particular reason why this isn't working? 有什么特殊原因为什么不起作用?

Here's my code: 这是我的代码:

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!");
            }
        });
    }

You can use recurrcive function as 您可以将递归函数用作

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM