【发布时间】:2016-11-07 04:55:08
【问题描述】:
好的,所以我花了最后一天试图弄清楚一些事情,我对编码比较陌生,所以如果它一团糟,我很抱歉。我目前正在开发一个请求 JSON 的机器人,这是我目前拥有的代码
const request = require('request');
const bodyParser = require('body-parser');
global.count = 10;
for (var i = 1; global.count === 10; i++) {
var options = {
url: 'https://www.the100.io/api/v1/groups/2127/users?page=' + i, //Returns 10 entries per page, so loop is to navigate pages
headers: {
'Authorization': 'Token token="Hidden for Privacy"'
}
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body); //Also need a way to append to info as to add on as the loop progresses, still need to look that up though
console.log(JSON.stringify(info, null, 1)); //Logs the body
global.count = info.length; //Will return the value 10, until there are no more entries and then will terminate loop
}
}
request(options, callback);//Sends request
}
//It just keeps running the loop and doesn't execute the request at the bottom which is what will make the loop terminate, I've tried many things with
//callbacks and nothing has worked so far
我似乎无法使循环正常运行,我不想寻求帮助,但我被困住了,我很难过。提前谢谢。
【问题讨论】:
-
循环终止条件始终为真。
global.count = 10返回10,即true。=是赋值,===是比较。但是,即使您确实修复了该问题,它也不起作用,因为在循环终止之前无法执行回调,但只有在回调运行并设置正确的值时,循环才能终止。这篇文章对于理解 JavaScript 的处理模型非常重要:developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop。 -
您的循环终止条件始终为真,因为您在条件中进行了分配。将其更改为
global.count === 10以修复该部分。然后您将遇到的另一个问题是您的request()s 将是异步的,因此最终请求可能会在其他请求之一之前完成,然后将global.count = 0;设置为仅被先前的请求之一覆盖。您可能不应该尝试在循环中执行此操作,而是调用一个发出请求的函数,然后当该请求完成时,使用下一页发出请求,依此类推,直到您拥有所有页面。 -
@Dymos:回调永远不会被执行,因为循环阻塞了其他一切。
-
@FelixKling 啊,好电话。
-
@FelixKling 那么是否有另一种方法可以获得我正在寻找的相同输出?根据我的阅读,我认为循环是唯一的方法。
标签: javascript json node.js callback