Named function to avoid callback HELL not working

hi everybody for those of you who struggled about the “named function to avoid callback hell” exemple provided by Mosh in his course I have found the solution.

In the exemple he provides he give the same name to 2 different function:
getRepositories and getCommits. I have spent a good amount of time and I just found the fix; give the functions diffente names. In my case I have added a number to the named function.

Have a look at my code bellow,

console.log(‘Before’);

getUser(1, getRepositories1);

console.log(‘After’);

function getRepositories1(user){
getRepositories(user.gitHubUsername, getCommits1);

}

function getCommits1(repos) {
getCommits(repos,displayCommits);
}

function displayCommits(commits){
console.log(commits);
}

function getUser(id, callback){
setTimeout(() =>{
console.log(‘Reading db…’);
callback({id: id, gitHubUsername: ‘mosh’});
}, 2000);
}

function getRepositories(username, callback){
setTimeout(() => {
console.log(‘Reading database…’);
callback( [‘repo1’, ‘repo2’, ‘repo3’]);
}, 2000);

}

function getCommits(repo, callback){
setTimeout(() => {
console.log(‘Reading DB to display all commits…’);
callback([‘commit1’,‘commit2’,‘commit3’]);
}, 2000);

}

1 Like

Thanks,

Yeah you can’t have two functions with the same name. I followed the same convention as he did with displayCommits() before showing the rest of the solution.

I think he made a mistake since he never tests the code in this lesson. It would have blown up with errors.

I don’t like this solution anyway because you dirty up the code space with 2 function names for every bit of functionality. Also calling a function getSomething implies that it will return a value that can be stored in a variable and used outside the function which is not the case when dealing with async functions so displaySomething() or doABunchOfStuffWithSomethingAndThenBeDoneWithItButDontTryGoingOutsideThisFunctionWithSomething() are more appropriate function names :slight_smile:

2 Likes

As far as I know, in JS we cant give the same name to two different functions so the solution he explain in lesson 5 Named Functions to Rescue, is not correct at all.
@Samaty Thanks for your explanation

Hi,
I have had the same problem and wasted a lot of time in it.
I don’t understand why is not fixed.
Thanks