I found 2 variation like 1. deferred.resolve(); 2. deferred.resolve(data);
after service response. What is the difference between 2. Which one I have to use strictly.
I found 2 variation like 1. deferred.resolve(); 2. deferred.resolve(data);
after service response. What is the difference between 2. Which one I have to use strictly.
First scenario:
function getPromise() {
var deferred = $q.defer();
deferred.resolve();
return deferred.promise;
}
getPromise().then(
function(data) {
console.log(data); // Output "undefined"
}
);
Second scenario:
function getPromise() {
var deferred = $q.defer();
var data = "hello";
deferred.resolve(data);
return deferred.promise;
}
getPromise().then(
function(data) {
console.log(data); // Output "'hello'"
}
);
So it all about on how you resolve the promise, with or without passing information to the function in the resolved promise.
When you call a service, it mean that you're waiting for a server's response. The response could be a simple success or some data.
myServiceFunction = function() {
var deferred = $q.defer();
$http.post/get(myURL,someData/*not mandatory*/)
.success(function(response){ // you get into this function when everything goes right
deferred.resolve(response); //your sending back the server's response to your controller (or whatever has called this function)
})
.error(function(response){
deferred.reject(response); // your also sending back the server's response but using reject means that something gone wrong on server call
})
return deferred.promise; // don't forget to send the promise!!
}
In the example above I'm sending the response server back to the one which has called the service function.
But if you just need to know that the request succeeded then a simple deferred.resolve()
is enough (and deferred.reject()
- to tell that it didn't succeed).
To make it shorter, here's what you should know:
deferred.resolve()
- means request succeededdeferred.reject()
- request faileddeferred.resolve(data)
- means request succeeded and here's some datadeferred.reject(data)
- request failed and here;s some dataHope it's clear enough