0

I have a service(factory) that uses another service to fetch data.Something like this:

factory('myFactory', function(anotherFactory) {

     var factoryObject = {};

     factoryObject.myMethod = () {

          var newObjectToReturn;

          // async call
          anotherFactory.get(id, function(data) {

              // do some processing
              newObjectToReturn = data; 
          });

          return newObjectToReturn;
     }
   return factoryObject;
});

Now, problem is of course, that because of asynchronous call, factoryObject.myMethod() always returns undefined, because return newObjectToReturn is first executed, and I can't simply return data. Is there any way around this ?

Zed
  • 5,683
  • 11
  • 49
  • 81
  • Assuming your factory uses $http you should return the promise. See http://stackoverflow.com/a/17646781/1522169 – noj Oct 15 '14 at 08:49

1 Answers1

-1

return the response data in callback

factory('myFactory', function(anotherFactory) {

 var factoryObject = {};

 factoryObject.myMethod = () {

      var newObjectToReturn;

      // async call
      anotherFactory.get(id, function(data) {

          // do some processing
          newObjectToReturn = data; 
      },function(response){
           return newObjectToReturn;
      });
 }

return factoryObject; });

Nandish
  • 125
  • 2
  • 11