javascript - 当您不知道页数时,如何使用 Node.js 在 while 循环中向 API 发出多个分页 GET 请求?

标签 javascript json node.js rest asynchronous

我正在使用 REST JSON API,它无法提供查询页面或条目总数的方法。但我需要循环向 API 发出多个请求才能获取所有可用数据。

搜索了许多 stackoverflow 问题后,我能找到的最接近的工作解决方案成功发出了多个请求,但仍然要求您知道最后一页是什么:

这有效:

const async = require("async");
const request = require("request");

let page = 1;
let last_page = 20;
let json;

async.whilst(function () {
    // condition here
  return page <= last_page
},
function (next) {
  request(`https://driftrock-dev-test-2.herokuapp.com/purchases?${page}&per_page=20`, function (error, response, body) {
    if (!error && response.statusCode == 200) {
    json = JSON.parse(body);
        console.log(json.data);      
        console.log(page);
    }
    page++;
    next();
  });
},
function (err) {
  // All things are done!
});

我尝试对其进行稍微调整以适应我不知道最后一页(如下)的要求,但我无法弄清楚如何使逻辑正确或如何解决获取 的异步问题json 变量未定义。我需要获取 json.data 数组的值来确定包含来自 API 响应的所有对象数据的数据数组的长度。

这不起作用 - 返回未定义:

const async = require("async");
const request = require("request");

let page = 1;
let json;

async.whilst(function () {
    // condition here
  json.data.length !== 0
},
function (next) {
  request(`https://driftrock-dev-test-2.herokuapp.com/purchases?${page}&per_page=20`, function (error, response, body) {
    if (!error && response.statusCode == 200) {
    json = JSON.parse(body);
        console.log(json.data);      
        console.log(page);
    }
    page++;
    next();
  });
},
function (err) {
  // All things are done!
});

我已经研究这个问题很长时间了,所以任何帮助将不胜感激!谢谢!

最佳答案

你的逻辑有一些问题。首先,您不会同时在测试函数中返回验证。但即使您这样做了,您也是在针对 undefined variable 进行测试。因此验证将失败并在第一次迭代之前退出您的代码。

let oldPage = 1;
let nextPage = 2;
let json;

async.whilst(function () {
    // Check that oldPage is less than newPage
  return oldPage < nextPage;
},
function (next) {
  request(`https://driftrock-dev-test-2.herokuapp.com/purchases?${oldPage}&per_page=20`, function (error, response, body) {
    if (!error && response.statusCode == 200) {
    json = JSON.parse(body);
        console.log(json.data);      
        console.log(oldPage);
    }
    if (json.data.length) {
      // When the json has no more data loaded, nextPage will stop 
      // incrementing hence become equal to oldPage and return 
      // false in the test function.
      nextPage++;
    }
    oldPage++;
    next();
  });
},
function (err) {
  // All things are done!
});

这样您就可以看到不再有新页面可显示的那一刻。

关于javascript - 当您不知道页数时,如何使用 Node.js 在 while 循环中向 API 发出多个分页 GET 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48339532/

相关文章:

javascript - 从 Javascript 自动播放视频元素在 iOS Safari 上不起作用

javascript - 迭代 JSON 将结果放入数组

javascript - 无法将 Web 服务器的 JSON 结果写入 html

json - 检查对象在 json4s/lift-json 中是否有字段

node.js - 如何在Nodejs中导出文件之间的 session 变量?

node.js - 在 Node 中创建 REST API 时,如何将来自对外部网站的请求的 http 响应流式传输到原始 api 调用?

javascript - 尝试调用 API 端点时 Next 不是函数

javascript - 单击图标后不显示日历,但单击输入字段后显示

javascript - AngularJS 和 Protractor - 如何检查元素是否显示?

Javascript 和 AI,事实还是虚构?