Nicholas
Nicholas

Reputation: 3757

Javascript - How to put a callback in a callback?

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();
});

Upvotes: 0

Views: 56

Answers (1)

Paul
Paul

Reputation: 141937

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 ) );

Upvotes: 1

Related Questions