0

I have read this:

Callback in a callback?

And I still do not understand how I am meant to do it. Sorry, I am a Python programmer and only just starting to understand JavaScript.

I have this function:

this.getName(function() {
alert("Done");
});

Which has a callback to here:

this.getName = function(callback){
    *doing something*
    callback();
}

Which works great. The alert doesn't go off until getName() has finished.

However I have another function, which needs to be run after getName() has been run and completed:

this.getDetails = function(){
  *Does something*
}

But I haven't got a clue how it is meant to be implemented. I have tried putting it in the first function, but it doesn't work. Any help would be much appreciated!

I have tried this:

this.getName(function(getDetails) {
alert("Done");
this.getDetails();
});
ScoutEU
  • 2,738
  • 10
  • 33
  • 64

1 Answers1

1

Instead of alerting "done", just call getDetails (or do both):

this.getName( _ => {
    this.getDetails();
} );

I switched to an arrow function to use lexical this, but if you don't want to use an arrow function you can also use bind:

this.getName( function ( ) {
    this.getDetails();
}.bind( this ) );

or just:

this.getName( this.getDetails.bind( this ) );
Paul
  • 130,653
  • 24
  • 259
  • 248
  • @ScoutEU The problem with what you had tried was that you lose `this` context when you call a function like `func()` instead of `obj.func()`, so you need to use one of these solutions to preserve your value of `this`. See this question for more details about that: https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Paul May 12 '18 at 18:36
  • Paul. Thank you so much. Works perfectly. Spent several hours trying to work everything out, and it was as 'simple' as this! THANK YOU! I will mark your answer as accepted as soon as I can. – ScoutEU May 12 '18 at 18:40