BigBoy1337
BigBoy1337

Reputation: 4963

Can you explain this Javascript callback function to me?

If I have the following callback function:

a(function  () {
  b() 
})

my understanding is that a would be executed first, then b once a is finished

But generally in programming, you pass parameters to a function within the parantheses right? So in this function, it seems as though you are passing

function  () {
  b() 
}

to the function a as an argument. So according to what I know about programming, a should execute with all of that as an argument right?

Yet according to what I know about callbacks, it means instead, that all of that executes after the a function executes. Can you see the contradiction? Also, then wouldn't the function a be executing without parameters?

Do parameters just work differently in javascript. By default, does all the stuff in the parentheses execute after the function itself?

Upvotes: -1

Views: 118

Answers (1)

adeneo
adeneo

Reputation: 318182

The a() function would have to have an argument that is actually a callback, it doesn't just work automagically

function a(callback) {  // callback argument
    // do lots of stuff

    callback(); // call the function after stuff has been done
}

a(function() {
    b();
});

And you could also just do

a(b);

and pass arguments to the callback

function a(callback) {  // callback argument
    // do lots of stuff

    callback(param1, param2, param3);
}

a(function(param1, param2, param3) { // here we get them back
    b(param2); // and we can pass them along
});

This is especially useful with async behaviour

function a(callback) {  // callback argument

    $.ajax({
        // ajax arguments
    }).done(function(returned_data) {

        callback(returned_data);

    });

}

a(function(returned_data) { // data from the ajax call
     // do something with returned_data
});

That's just an example, $.ajax returns a promise that is more handy to use, but it shows how a callback would work with async functions.

As a sidenote, you'll often see code where a callback is not guaranteed, and then it makes sense to check if there was a callback function passed as an argument before trying to execute it to avoid errors.

function a(callback) {  // callback argument
    // do lots of stuff

    if (typeof callback === 'function') {
        callback();
    }
}

Upvotes: 5

Related Questions