更新Javascript中的全局变量时遇到问题
问题描述:
我在更新节点应用程序中的全局变量时遇到问题。有人可以看我的代码,并让我知道发生了什么问题吗?我定义了一个dowhile循环来运行,只要我的HTTP响应对象没有定义“next”。在循环内部,事情按预期运行并定义了new_json.next,但while条件返回错误,因为new_json.next在那里未定义。我有点新的Javascript,所以不知何故,我的变量范围是关闭的,但我不知道如何正确地做的事情根据其他问题。更新Javascript中的全局变量时遇到问题
function make_pagination_request(json, create_response_data) {
var new_json={};
do {
var options = {
host: slug + '.nationbuilder.com', //should be replaced to be site-agnostic
path: json.next,
method: "GET",
json: true,
headers: {
"content-type": "application/json",
"accept": "application/json"
},
}
var req = https.get(options, req_callback);
function req_callback(response) {
response.on('data', function(chunk) {
str += chunk;
});
response.on('end', function(new_json) {
new_json=JSON.parse(str);
new_results = new_json.results
results= results.concat(new_results);
console.log("combinedlength: " + results.length)
console.log(new_json.next);
});
}
} while (new_json.next.includes("api"));
答
问题是HTTPs请求是异步的,而do/while循环是同步的。在这种情况下,在将包含next
的值分配给new_json
变量之前,会达到while语句。
当第一次回调函数还没有调用while语句时。因此,new_json
的值是{}
(初始值),它缺少next
。因此,您遇到的错误。
但是,解决方案并没有解决初始值为new_json
。解决方案是删除do/while循环并继续在HTTP请求回调中工作。
答
这是我工作的代码。谢谢yeiniel。我最终只是简单地从本身的最后调用函数make_pagination_request。我还做了一些与原始问题无关的其他更改,但这些更改对于调试是必需的。
function make_pagination_request(json, create_response_data, callback, tokens, options) {
path = json.next + "&access_token=" + tokens[slug];
var options = {
host: slug + '.nationbuilder.com', //should be replaced to be site-agnostic
path: path,
method: "GET",
json: true,
headers: {
"content-type": "application/json",
"accept": "application/json"
},
}
var str='';
var req = https.get(options, req_callback);
function req_callback(response, create_response_scripts) {
response.on('data', function(chunk) {
str += chunk;
});
response.on('end', function() {
new_json=JSON.parse(str);
new_results = new_json.results
results= results.concat(new_results);
console.log('combined_length: ' + results.length)
if (new_json.next) {
make_pagination_request(new_json, create_response_data,create_response_scripts, tokens, options);
} else {
create_response_data(results, query, create_response_scripts);
}
});
}
}
我应该知道这是类似的东西。这是我才开始理解的,也是我其他一些问题的根源。我最终只是简单地从本身的最后调用函数make_pagination_request。 –
Javascript代码和包含在该语言中的同步构造的异步性质一直是很多程序员的一个很大的问题来源。我在你的评论中看到,你设法通过再次调用相同的函数来解决问题。即使它工作,我建议你研究一个更好的解决方案,因为如果函数调用自己多次,你将会遇到堆栈溢出问题。 – yeiniel
我以为我已经达到堆栈溢出问题 –