The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
data) every time to solve promises, instead, you can simply return response. data in then() 's callback. The then() function returns a new promise, so isn't need to use $q to create a deferred object and return a promise. Just return the promise created by then() .
What Is Promise in Angular? Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time.
A resolved promise means, that the code handled by the promise is done, and the code in the callback passed to the then method is executed with the resolved value passed in.
Short answer: Yes, you can resolve an AngularJS promise before you return it, and it will behave as you'd expect.
From JB Nizet's Plunkr but refactored to work within the context of what was originally asked (i.e. a function call to service) and actually on site.
Inside the service...
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....
somethingService.getSomething(5).then(
function(thing) { // On success
alert(thing);
},
function(message) { // On failure
alert(message);
}
);
I hope it helps someone. I didn't find the other answers very clear.
Resolved promise:
return $q.when( someValue ); // angular 1.2+
return $q.resolve( someValue ); // angular 1.4+, alias to `when` to match ES6
Rejected promise:
return $q.reject( someValue );
Here's how I typically do it if I want to actually cache data in array or object
app.factory('DataService', function($q, $http) {
var cache = {};
var service= {
getData: function(id, callback) {
var deffered = $q.defer();
if (cache[id]) {
deffered.resolve(cache[id])
} else {
$http.get('data.json').then(function(res) {
cache[id] = res.data;
deffered.resolve(cache[id])
})
}
return deffered.promise.then(callback)
}
}
return service
})
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With