It's becoming clear to me that there is a piece of the puzzle missing when it comes to understanding exactly when certain function outputs are available in JavaScript.
In my Angular application, I am trying to extract a user's initials by extracting the first letters of their first and last names from API data using two separate functions. These functions are functioning properly, displaying the correct results in the console:
getFirstNameFirstLetter() {
if (this.authenticationService.isAuthenticated()) {
const userObj = JSON.parse(sessionStorage.getItem('currentUser'));
const userInfo = userObj.data;
const firstName = userInfo.name.first;
const firstNameFirstLetter = firstName.trim().charAt(0);
console.log(firstNameFirstLetter);
return firstNameFirstLetter;
}
}
getLastNameFirstLetter() {
if (this.authenticationService.isAuthenticated()) {
const userObj = JSON.parse(sessionStorage.getItem('currentUser'));
const userInfo = userObj.data;
const lastName = userInfo.name.last;
const lastNameFirstLetter = lastName.trim().charAt(0);
console.log(lastNameFirstLetter);
return lastNameFirstLetter;
}
}
However, where I'm encountering confusion is when attempting to use the values returned by these functions to generate the user's initials:
getInitials(firstNameFirstLetter, lastNameFirstLetter) {
if (this.authenticationService.isAuthenticated()) {
if (!this.firstNameFirstLetter || !this.lastNameFirstLetter) {
console.log('Names not ready!');
return;
} else if (this.firstNameFirstLetter && this.lastNameFirstLetter) {
console.log(firstNameFirstLetter + lastNameFirstLetter);
return firstNameFirstLetter + lastNameFirstLetter;
}
}
}
Every time I try to pass the outputs of the previous functions into getInitials(), "Names not ready!" gets printed to the console.
For context, I am invoking these functions within Angular's ngOnInit lifecycle hook as follows:
ngOnInit() {
this.getFirstNameFirstLetter();
this.getLastNameFirstLetter();
this.getInitials(this.firstNameFirstLetter, this.lastNameFirstLetter);
}
The crux of the issue lies in what values are accessible at what points, as evidenced by receiving 'undefined' values when debugging the inputs passed to getInitials(). This indicates that the function is being executed before the other two have completed, hence prompting 'Names not ready!' to be logged. The question then becomes, what fundamental architectural concept am I overlooking to address this dilemma?