Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript AngularJS Basics (1.x) Services in Angular Using Services To Save and Delete Data

dataService.getTodos() call

After watching the view l was sort of wondering a view thing. why was the service not called in this way

$scope.todos = dataService.getTodos(function(res) {
            console.log(res.data);
            $scope.todos = res.data;
        });

However was called in this way instead

dataService.getTodos(function(res) {
            console.log(res.data);
            $scope.todos = res.data;
        });

Both seems to do the same job and first one makes so much more sense to me. What's the pros and cons of using either of these?

Thomas Nilsen
Thomas Nilsen
14,957 Points

Alright - Let's talk about the first example

$scope.todos = dataService.getTodos(function(res) {
            console.log(res.data);
            $scope.todos = res.data;
        });

The only reason this works is because you write $scope.todos = res.data; inside the callback function as well.

If you were to write it like this:

$scope.todos = dataService.getTodos(function(res) {
            console.log(res.data);
        });

It wouldn't work.

This function is asynchronous - meaning you won't get back a value right away. You have to get it inside the callback function.

This is an important aspect of javascript.

I would recommend reading this