0

If I have a factory where I want to return all tasks:

App.factory('Task', function(TaskResource) {
  return {
    all: function() {
      TaskResource.query().then(function(results) {
        return results;
      }  
    }
  };
});

and I try to use it in the "TasksController":

App.controller('TasksController', function('Task') {
  $scope.tasks = Task.all();
});

I get the result of 'undefined'. If I log the results in the factory itself, they return correctly. Can someone help me understand why this is happening? Thanks.

1 Answer 1

1

TaskResource.query() is a promise. .then on the promise returns after some time. What that means is the all function returns immediately, returning undefined. Promise completes after some time and returns the result which nobody gets! That is the reason why you see undefined returned from all function.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the explanation. Do you know how I could modify this so that it would return the result of the promise?
Since your return value depends on a promise, you should return a promise as a result of all function. You may return TaskResource.query() promise or return a new promise and resolve it when TaskResource.query() resolves.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.