-1

I'm trying to run the following function

var getjson = function(){
    $.get('/api/todos/testing', function(results){
        return results;
    });
}

The results should look like this:

[{_id: "57803baf0a76d5c924b18ca2", username: "testing", toDoTask: "Buy Water", isDone: false, __v: 0},{_id: "57803baf0a76d5c924b18ca3", username: "testing", toDoTask: "Buy Milk", isDone: false, __v: 0}]

When I try to call the function to append the list to my Angular controller

angular.module('firstapp').controller('todos', function(){
   this.list= getjson();
});

The list does not save the values returned by the function.

I'm sure the problem is related to the way I'm trying to return the results but I couldn't find what's the right way to do it.

Geoffrey-ap
  • 380
  • 3
  • 12

1 Answers1

2

$.get is asynchronous so when you ran getjson(), the code will still do the GET operation but it will return straight away.

Since you did not define a return statement for it, by default javascript will give you back undefined which is what this.list will be set as.

Documentation for $.get: https://api.jquery.com/jquery.get/

To fix your problem the easiest way would be to make getjson() accept a callback function.

Example:

var getjson = function(done){
    $.get('/api/todos/testing', function(results){
        return done(results);
    });
}

Then you will call getjson() with a function that sets the list.

angular.module('firstapp').controller('todos', function(){
   getjson(function(results) { this.list = results; }));
});
Samuel Toh
  • 18,006
  • 3
  • 24
  • 39
  • Doesn't it return a promise? If so, this answer might be more helpful if it showed how to pass a resolution function to the promise. – danh Jul 09 '16 at 00:22