0

How can get value from the Promise return by $http service

>d {$$state: Object}
 $$state: Object
 status: 1
 value: Array[1]
 __proto__: Object
 __proto__: Object

How to get the value in the d object

s.states = '';
$http.get('/api/random').then(function(response) {
  s.states = response;
 }, function(error) {

}).finally(function() {

})
console.log(s.states);

which shows the above result. $$state so how can get the value from it?

2
  • have you tried d.value ? Commented Sep 12, 2016 at 6:14
  • By calling promise.then(function(value) { acessValueHere(value); }), as for all promises. Read blog.ninja-squad.com/2015/05/28/angularjs-promises Commented Sep 12, 2016 at 6:18

1 Answer 1

1

As suggested above:

promise.then(function(value) { 
      // Value contains the data received in the response
   }, function(error) {
      // This is called when error occurs.
   }
)

The promise itself does not contain a value. It returns the value in the future ("promises" to return a value) when it's available. And when it becomes available (or not), one of two callbacks passed to then() methods gets triggered. So basically, you should make calls like this:

$http.get('/api/random').then(function(response) {
    // Do some stuff with response.
});

You can pass a callback to finally() method callback, which will be run regardless of success or error in promise.

$http.get('/api/random').then(function(response) {
    // This one is triggered in case of successful response.
}, function(error) {
    // This code runs in case of error
}).finally(function() {
    // And this block will be triggered anyway after the promise returns.
});
Sign up to request clarification or add additional context in comments.

5 Comments

You probably need to check the Network tab of your developer tools to see what you request and what you get in response.
i print the response it shows the above result $$state object
Based on the code snipped you added: "console.log(s.states);" executes BEFORE "s.states = response"; So basically it should print empty string assigned above. The output above shows that you are trying to print the promise itself (like console.log($http.get(...)), and $$state.status equal to 1 means that the promise is already resolved. Try console.log(response) in the first callback and inspect what it logs.
i want the result outside the $http
That's how promises work. You cannot stop the code execution and wait until promise returns. However, your scope is still available in the callbacks, so you can use anything you need in combination with response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.