How can I parse this result in angularjs promise

I have such a service

app.service('newsService', function($q, $timeout,$http) {

  this.getNewsName = function(id) {
    var deferred = $q.defer();
    var newsId = parseInt(id, 10);

    $timeout(function() {

         $http({
                url: "entry/GetNewsTitle",
                 method: "POST",
                 data: $.param({'id':newsId}),
                 headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
                    })
                    .success(function(data, status, headers, config) {

                        deferred.resolve(data.name);
                    })
                    .error(function(data, status, headers, config) {
                        console.log('failed');
                    });
                }, 10);

    return deferred.promise;
  } 

console.log(deferred.promise)in another function gives me three functions "catch", "finally" and "then", but how can I get back to data.name?

+4
source share
2 answers

Like this:

newsService.getNewsName(id).then(function(name) {

});
+4
source

First of all, you should optimize the maintenance method to avoid deferred anti-patterns . You do not need to create a dummy deferred object, as it $http(...)already returns Promise.

The service will look like this:

app.service('newsService', function($http) {

    this.getNewsName = function(id) {
        return $http({
            url: "entry/GetNewsTitle",
            method: "POST",
            data: $.param({
                'id': parseInt(id, 10)
            }),
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function(data, status, headers, config) {
            return data.name;
        }).error(function(data, status, headers, config) {
            console.log('failed');
        });
    };

});

Note that it getNewsNamereturns a result $http.

A controller consuming this service will be bound to it using the Promise API:

newsService.getNewsName(123).then(function(name) {
    console.log(name);
});
+2
source

All Articles