0

This is an example where we use Asynchronus Javascript to simulate retrieving the list of commits for a Github user's repositories.

getUser(1, (user)=>{
    getRepositories(user.githubUsername, (repos)=>{
        getCommits(repo , (commits)=>{
            // This is callback hell\
        });
    });
});

function getCommits(repo){
    return ['commit1','commit2'];
    }

function getRepositories(username, callback){
    setTimeout(()=>{
        //Just for simulation
        console.log('Retrieving repos');
        return ['repo1','repo2'];
        },2000);

function getUser(id,callback){
    setTimeout(()=>{
        console.log('Reading user from database');
        callback({id: id, githubUsername: 'myName'});
        },2000)
}

I want to print out the number of commits for each repository (just commit1 and commit2 for simplicity)... I know how to achieve this Synchronously... but is this implementation correct for doing it Asynchronously ? when getUser() is called... what executes after? the lambda function or the actual function?

Zaham2
  • 337
  • 1
  • 4
  • 11
  • Did you already test it? If no, _why not_? If yes, _why_ the questions? – Andreas Dec 30 '19 at 12:19
  • Not quite sure what you are asking about, but the obvious issues with your code are that `getRepositories` doesn't call `callback` and that `getCommits` is passed a callback but doesn't define a corresponding parameter nor call it. – Felix Kling Dec 30 '19 at 12:19
  • [How to explain callbacks in plain english? How are they different from calling one function from another function?](https://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-o) – Andreas Dec 30 '19 at 12:21
  • I just tried it. getCommits() is never called... I don't know why – Zaham2 Dec 30 '19 at 12:23
  • Its the nested structure that I'm having trouble understanding. I can't tell whether the outer or the inner function is executed first – Zaham2 Dec 30 '19 at 12:24
  • _"`getCommits()` is never called"_ -> Felix has already explained why that is. `getRepositories` doesn't call `callback` (which would call `getCommits()`) – Andreas Dec 30 '19 at 12:27
  • *"I can't tell whether the outer or the inner function is executed first"* Would it be easier for you to see if you separate the function definition from passing it? Consider `function foo() {} ; bar(foo);`. It should be clear that you are not actually calling `foo` here anywhere. You are calling `bar` and pass `foo` as argument. So `bar` is executed first and will eventually call `foo` (presumably, depends on its implementation of course). **Defining** a function and **calling** a function are two different things. – Felix Kling Dec 30 '19 at 12:29
  • @FelixKling Many thanks. that clears things up a bit. Make it an answer so I can best answer it : ) – Zaham2 Dec 30 '19 at 12:38

0 Answers0