好吧,所以我花了最后一天试图找出一些东西,我比较新的编码,所以如果它的一个烂摊子,我很抱歉。我目前正在对请求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的处理模型非常重要:https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop。 –
您的循环终止条件始终为真,因为您在条件中分配。将其更改为'global.count === 10'来修复该部分。接下来你要运行的另一个问题是你的request()将是异步的,所以最终的请求可能会在其他请求之前完成,然后设置'global.count = 0;'只被覆盖之前的请求之一。您可能不应尝试在循环中执行此操作,而应调用发出请求的函数,然后在完成请求时,使用下一页进行请求等等,直至获得所有页面。 – Dymos
@Dymos:回调将永远不会执行,因为循环阻塞了其他所有内容。 –