Reputation: 6593
Playing around with angular resource i cant figure out why it works this way. I have following code (let's assume that query function works fine):
$scope.getSomething = function (someObject) {
var result;
Factory.getSomething.query({ id: someObject.id }).$promise.then(function (success) {
alert('success');
result = 'success';
},
function(error) {
alert('error');
result = 'error';
});
alert(result);
};
When i execute this method i get following: 1) Alert with undefined 2) Alert with 'success'
Why undefined is first? As I understand $promise right, then
alert('success');
result = 'success';
should work first if succeed (when asynchronous is executed).
Then should be invoked last alert with result
value.
But seems like it works not like i am expecting.
Any suggestions? Thanks in advance.
Upvotes: 1
Views: 83
Reputation: 21207
Unless there's a particular reason that you need to deal with the raw $promise returned by $resource I find it a lot easier to just use the built in success/failure handlers.
Factory.getSomething.query({id: someObject.id}, function(data) {
// this will be asynchronously called when the API call returns with success. data is your payload
}, function(error) {
// this will be asynchronously called when the API call returns with error
});
Upvotes: 0
Reputation: 2446
The promise means that while it's processing it allows other code to run. Therefore while your getSomething
request is being processed on the server your browser is running the rest of the code, in this case the alert(result)
.
At that point result
hasn't yet been assigned so it's undefined
. Then your web service returns, and the success code runs with runs the "success" alert
which is the second alert message you're getting.
Upvotes: 2
Reputation: 28368
You are alerting result
before it's defined, therefore you get an alert with undefined
. result
only gets a value after the async operation has been completed, either in your then
or error
.
Upvotes: 0