Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use angular and JavaScript promises to return some data?

I am trying to grab some data from local storage, but I want to use the date once is ready. something like:

// this belongs to a Helper factory
getData: function(){
        var deferred = jQuery.Deferred();
        setTimeout(function(){
            var data = {
                description: localStorageService.get('description'),
            };
            deferred.resolve()
        }, 10);
        return deferred.promise();
  },

// I set it up so that in the controller I can do
// $scope.data = Helper.getData();

Similar to the example i have, i just want to return the data object once it has the description from localstorage

I am using angularjs, so i want to display {{data}} in my view once the promise is resolved. like maybe use ng-hide or something similar.

In any case, my question is about setting up that promise.

Any ideas?

like image 472
Patrioticcow Avatar asked Feb 13 '23 07:02

Patrioticcow


2 Answers

$timeout() returns a promise, so this works:

getData: function(){
   return $timeout(function(){
       return localStorageService.get('description'),
   },3000);
}

usage:

getData().then(function(data){
   console.log(data);
})
like image 157
pixelbits Avatar answered Feb 15 '23 10:02

pixelbits


Well $q is the library normally used for handling promises in angularjs, since you're reading from local storage and that is a synchronous operation I'm not sure why you want to return a promise, the way this is usually done in angular however is like this:

getData: function(){
   var deferred = $q.defer();
   $timeout(function(){
     var data=localStorageService.get('description'),
     deferred.resolve(data);
   },3000);
   return deferred.promise;
}

usage:

getData().then(function(data){
   console.log(data);
})
like image 26
Mohammad Sepahvand Avatar answered Feb 15 '23 09:02

Mohammad Sepahvand