0
我使用最简单的库从api中获取所有数据,该数据由偏移量和限制参数分割,并且没有有限数量的结果。Node.js - http请求在while循环中不起作用
我使用while循环遍历数据,并且在没有返回结果的地方,我通过将'incomplete'变量设置为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或其他东西。 – Anistark
您试图一起使用异步和同步代码。 while循环发送太多的请求,并且你得到堆栈大小错误。使用http://caolan.github.io/async/或尝试创建promises数组,然后通过Promise.all运行它。希望这可以帮助。 –
要使循环暂停以完成异步操作,请查看'fibers/future','fut.wait()'在循环体的末尾,'fut.return()' '.end'正文(仅限于_nodejs_) –