【问题标题】:Node.js - http request is not working when inside a while loopNode.js - 在while循环内时http请求不起作用
【发布时间】:2016-11-20 14:58:59
【问题描述】:

我正在使用 unirest 库从 api 中获取所有数据,这些数据由偏移量和限制参数分割,并且没有有限数量的结果。

我使用 while 条件遍历数据,在没有返回任何结果的地方,我通过将“不完整”变量设置为 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!");
            }
        });
    }

【问题讨论】:

  • 它应该可以工作。但是,当您的响应出现时,循环会更进一步。在瀑布模型或系列模型中使用 Async.io 或其他东西。
  • 您尝试同时使用异步和同步代码。 While 循环发送太多请求,您会收到堆栈大小错误。使用caolan.github.io/async 或尝试创建promise 数组,然后通过Promise.all 运行它。希望这会有所帮助。
  • 要让循环暂停以完成异步操作,请查看循环主体末尾的fibers/futurefut.wait(),以及.end 末尾的fut.return()的主体(仅在 nodejs 中可能)
  • 感谢您的建议,使用异步实用程序解决了我的问题!

标签: javascript node.js unirest


【解决方案1】:

你可以使用递归函数

function getServerData(offset){

//Your api service with callback.if there is a data then call it again with the new offset.

}
function getServerData(1);

【讨论】:

    猜你喜欢
    • 2017-05-03
    • 1970-01-01
    • 2014-02-14
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    相关资源
    最近更新 更多