Want to resolve an angularjs promise before you return it? Yes, you can resolve an AngularJS promise before you return it, and it will behave as you’d expect.
Inside the service…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function getSomething(id) { // There will always be a promise so always declare it. var deferred = $q.defer(); if (Cache[id]) { // Resolve the deferred $q object before returning the promise deferred.resolve(Cache[id]); return deferred.promise; } // else- not in cache $http.get('/someUrl', {id:id}).success(function(data){ // Store your data or what ever.... // Then resolve deferred.resolve(data); }).error(function(data, status, headers, config) { deferred.reject("Error: request returned status " + status); }); return deferred.promise; } |
Inside the controller….
1 2 3 4 5 6 7 8 |
somethingService.getSomething(5).then( function(thing) { // On success alert(thing); }, function(message) { // On failure alert(message); } ); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.