Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AngularJS Basics (1.x) Services in Angular Using Services To Get Data

Robin Malhotra
Robin Malhotra
14,883 Points

Where does the callback come from?

In this snippet,

this.getTodos = function(callback){
        $http.get('todos.json').then(callback)
    }

Callback is an argument to the function. But where/when will this be called? How does angular know what to pass as callback? Where is it coming from?

2 Answers

Matt F.
Matt F.
9,518 Points

Hi Robin,

callback will get invoked once the promise is resolved.

Let's assume this is the code:

//define myCallback function which accepts the ajax request's data as a parameter
var myCallback = function (data) {
    console.log('below we are logging out the data from the AJAX request!');
    console.log(data);
};

//define the function that handles the ajax request
var getTodos = function(callback){
        $http.get('todos.json').then(callback)
};

//invoke our function
getTodos(myCallback);

In the above snippet, we invoke the function that handles the ajax request and we pass it the myCallvack function as its callback parameter.

The GET request returns a promise, which is a 'thenable' object. Once the ajax request completes (success or failure) it resolves the promise and invokes the function within the .then.

Let's assume that the GET request succeeds. In that case, it will pass your todos data to the callback within the .then as a parameter. (As an aside, you would pass a second callback to handle cases where a failure occurs - or use .catch() with the failureCallback).

A different style, but one that would yield the same results, is to write the callback directly into the .then, like this:

var getTodos = function(){
        $http.get('todos.json')
            .then( function (data) {
                    console.log('below we are logging out the data from the AJAX request!');
                    console.log(data);
             })
};

getTodos();
0yzh 󠀠
0yzh 󠀠
17,276 Points

The callback will be called when getTodos is invoked. You are passing a function to the getTodos method and it will in turn, call that function that is being passed after it runs its code.

$http.get('todos.json').then(callback) // <-- it is being called here.