1

I'm trying to understand callbacks. I have this function I found:

fetchMessages ( projectId, callback ) {
  return $.ajax( {
    url: `/projects/${ projectId }/messages`,
    type: 'GET'
  }, callback );
},

And I call that function using:

fetchMessages( this.projectId, ( data ) => {
   this.messages = data.messages;
} );

I'm not understanding the callback part. Does the callback mean that when jQuery gets the messages then the callback would be the result?

1 Answers1

2

when a AJAX is called, the javascript starts executing the next lines of code and does not wait for the reponse (asynchronous). But then how do we deal with this? Callback is one of the answers.

A (callback) function is passed an argument to the function. The purpose of the former function(the callback) is to do some task when the latter function is finished with it's task. Other similar approaches are promises and generators.

plonknimbuzz
  • 2,594
  • 2
  • 19
  • 31
aashu
  • 105
  • 1
  • 14