Hey amazing people of the Internet, Pretty noobish question here, but I'm having a bit of a problem with some of this Javascript I wrote. Here's the code -
const req0 = http.request({
hostname: `api.trello.com`,
port: 443,
path: `/1/lists/5cb77e9ef180dd2bbb25acf2/cards?key=${trelloKey}&token=${trelloToken}&fields=name`,
method: `GET`
}, res => {
let str = '';
res.on('data', chunk => {
str += chunk;
});
res.on('end', () => {
try {
var level0Data = JSON.parse(str);
console.log(`Level 0: ${level0Data}`)
level0Data.forEach((k,v) => {
var id = k.id;
var name = k.name;
console.log(`${id} = ${name}`);
});
} catch(error) {
console.log(error);
}
});
});
req0.on('error', error => {
console.log(error);
});
req0.end();
level0Data.forEach(function(level0Names) {
// code here
});
The issue I'm having with this is that it keeps giving me an error stating that the level0Data is not defined
.
I know it's a pretty newbie question, but I'd appreciate some guidance with it.
Thanks!
Do you see that level0Data
is not defined in below scope? (MDN reference(Scope))
level0Data.forEach(function(level0Names) {
// code here
});
You must use level0data
inside of callback function.
// NOTE: Level0data is available only here, as you defined in this scope.
...
var level0Data = JSON.parse(str);
console.log(`Level 0: ${level0Data}`)
level0Data.forEach((k,v) => {
var id = k.id;
var name = k.name;
console.log(`${id} = ${name}`);
});
...
Or you can pass a function to handle callback.
function handle(str) {
var level0Data = JSON.parse(str);
console.log(`Level 0: ${level0Data}`)
level0Data.forEach((k,v) => {
var id = k.id;
var name = k.name;
console.log(`${id} = ${name}`);
});
level0Data.forEach(function(level0Names) {
// code here
});
}
...
try {
handle(str)
} catch(e) {
console.error(e)
}