1

I have this simple function js getItems(), inside I call a services items.getItems(..) , I would like that the function return me a data. I tried to associate the var to function but the result is undefined

function getItems() {
            var resolvedValue;
            var deferred = $q.defer();
            items.getItems(function(data) {
            deferred.resolve(data);
            });
            deferred.promise.then(function(result) {
             resolvedValue=result; // it contains my information
            });
            console.log('v  alue%0' , resolvedValue); // it's undefined here!!!
            }
user880386
  • 2,737
  • 7
  • 33
  • 41

1 Answers1

0

items.getItems is async, so you have to use $q.promise

function getItems() {
  var deferred = $q.defer();
  items.getItems(function(data) {
    deferred.resolve(items);
  });
  return deferred.promise;
}

Read more here http://docs.angularjs.org/api/ng.$q

TruongSinh
  • 4,662
  • 32
  • 52
  • When I print the deffered.promise I don't see the data – user880386 Jan 25 '14 at 15:45
  • As said, please read more http://docs.angularjs.org/api/ng.$q to use a promise, usually `promise.then(function)`, or you can resolve it in the controller http://stackoverflow.com/questions/14980805/angularjs-resolve-with-controller-as-string/17039181#17039181 – TruongSinh Jan 25 '14 at 15:47
  • I read and i understood to do this :deferred.promise.then(function(result) { resolvedValue=result;}); but it is not visible outside the function.....it is not possible to do return resolvedValue – user880386 Jan 25 '14 at 19:02
  • As said, you do not return the value, you return the promise. That's what the promise is for. Please make a full fiddle with this service and another service or controller, where you make use of this service, we'll see how you can take the value from a promise. – TruongSinh Jan 25 '14 at 19:50