节点/JavaScript中的条件语句-超出调用堆栈大小
只要JSON的节点/JavaScript中的条件语句-超出调用堆栈大小,javascript,node.js,api,express,Javascript,Node.js,Api,Express,只要JSON的type字段中返回music值,我的脚本就会重新启动/发送GET请求 预期行为:运行GET调用,只要它返回type==“music”,但仍有一些运行以超过最大调用堆栈大小而结束 如何克服这个问题 JSON结构: { activity: "Solve a Rubik's cube", type: 'recreational', participants: 1, price: 0, link: '', key: '4151544', ac
type
字段中返回music
值,我的脚本就会重新启动/发送GET
请求
预期行为:运行GET调用,只要它返回type==“music”
,但仍有一些运行以超过最大调用堆栈大小而结束
如何克服这个问题
JSON结构:
{
activity: "Solve a Rubik's cube",
type: 'recreational',
participants: 1,
price: 0,
link: '',
key: '4151544',
accessibility: 0.1
}
代码:
我认为在while
关键字之后的条件下运行的代码无法访问do
块中的变量声明apirresulttype
。如果我没有弄错您的问题,您需要做的是在循环的正上方声明变量apirresulttype
,并在进入循环后更新该变量。这样,do块和while条件都可以通过闭包访问变量
//import components
const https = require("https");
const options = new URL("https://www.boredapi.com/api/activity");
//obtain data using GET
//loop till get data where type = 'music'
https
.get(options, (response) => {
//console.log('statusCode:', response.statusCode);
//console.log('headers:', response.headers);
// declaration happens outside of do block.
let apiResultType;
do {
response.on("data", (data) => {
//process.stdout.write(data);
let apiResult = JSON.parse(data);
// update the variable here, instead of initializing it. This block
// has access to the outer blocks' variables
apiResultType = apiResult.type;
console.log(apiResult);
});
} while (apiResultType == "music"); //error: apiResultType is not defined
})
.on("error", (error) => {
console.error(error);
});
我不确定这是如何抛出错误的,因为您拥有的是有效代码。一旦条件计算为false,do/while
循环结束,undefined不等于music的值。好的,我看到可变范围的东西在错误的位置。但是,代码可以工作,但返回JSON,其中类型
与音乐
不同。只要我得到type==“music”
//import components
const https = require("https");
const options = new URL("https://www.boredapi.com/api/activity");
//obtain data using GET
//loop till get data where type = 'music'
https
.get(options, (response) => {
//console.log('statusCode:', response.statusCode);
//console.log('headers:', response.headers);
// declaration happens outside of do block.
let apiResultType;
do {
response.on("data", (data) => {
//process.stdout.write(data);
let apiResult = JSON.parse(data);
// update the variable here, instead of initializing it. This block
// has access to the outer blocks' variables
apiResultType = apiResult.type;
console.log(apiResult);
});
} while (apiResultType == "music"); //error: apiResultType is not defined
})
.on("error", (error) => {
console.error(error);
});