B
B
beduin012015-12-06 13:26:02
JavaScript
beduin01, 2015-12-06 13:26:02

How to extract JSON from Promise?

I need to get JSON into a variable. However, due to JS being asynchronous, I get a Promise there.

$scope.stat_fromdb = $http.get('http://127.0.0.1:8080/stat').success(function(response) {
         // $scope.stat_fromdb = response.data;
         return response.data;
         console.log($scope.stat_fromdb);
    	
    	});
    	 console.log($scope.stat_fromdb);

The question is how to get JSON out of there?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Pavlov, 2015-12-06
@beduin01

Or take data from response inside callback

$http.get('http://127.0.0.1:8080/stat').success(function(response) {
         // используйте свои данные прямо тут 
         var data = response.data;
         console.log(data);
});

Or (if some external code needs the result) pass a callback outside - a function to be called when the data is ready.
var getData = function (callMeWhenDataReady) {
$http.get('http://127.0.0.1:8080/stat').success(function(response) {
         var data = response.data;
         console.log(data);
         // передайте данные во внешний callback
         callMeWhenDataReady(data);
});
};

...
getData(function(data) { 
        console.log(data);
} )
...

JS is asynchronous - you need to remember this and organize the code correctly. If you need to wait for several AJAX requests to continue doing something, you can also use jQuery.when() .

M
moondog, 2015-12-06
@moondog

$http.get('http://127.0.0.1:8080/stat').success(function(response) {
         $scope.stat_fromdb = response.data;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question