'Why does my return statement give undefined as the value when the console.log gives proper value?
I'm just trying to get the first object in the returned array from the database fetch and return the .class_name
value of that object. In the getClassName()
, the console.log()
prints the proper value I'm looking for, but the return statement immediately afterwards returns undefined
. It is called from the previous fetchClasses()
.
async function fetchClassesCanTeach() {
//fetch all classes
dbToken.then(token => {
return fetch(
// returns an array of classes
})
// if response okay return response
.then(async (response) => {
if (response.ok) {
return response.json();
}
})
// loop through courses
.then((testclasses) => {
testclasses.forEach((classes) => {
// create element for each course
const label = document.createElement('label');
var br = document.createElement('br');
//this makes checkbox for each class
label.htmlFor = "lbl" + classes.class_id;
label.appendChild(Createcheckbox(classes.class_id));
// getClassName() returns undefined
label.appendChild(document.createTextNode(getClassName(classes.class_id)));
label.appendChild(br);
document.getElementById('div2').appendChild(label);
});
})
// catch errors and show message
.catch((error) => {
clearAlerts();
showAlert(error.message);
});
}
function getClassName(classID){
//fetch class
dbToken.then(token => {
// returns an array of class objects based on classID
})
// if response okay return response
.then(async (response) => {
if (response.ok) {
return response.json();
}
})
// get class name
.then((classObjArray) => {
// Prints proper value
console.log(classObjArray[0].class_name);
// returns undefined
return classObjArray[0].class_name;
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|