0

I am confused about promise. I found the code below. What is the benefit of promise here. I have read about promise that it is used to avoid callback hell. Does promise provide better performance or is it just used to write the code in readable format?

     var list = function (params) {
            if (!params) {
                params = {};
            }
            var deferred = $q.defer();
            if (params.q) {
                params.q = JSON.stringify(params.q);
            }

            $http.get(someurl, {params: params}).success(function  (data, status, headers) {
                deferred.resolve(data);
            }).error(function (data, status, headers) {
                    deferred.reject(data);
                });
            return deferred.promise;
        };
Rohit
  • 2,987
  • 3
  • 25
  • 50
  • 1
    because the title is so vague, I've picked one of the many questions about Promises to make this a duplicate of. https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=site%3Astackoverflow.com%20what%20are%20promises – George Stocker May 25 '15 at 13:27

2 Answers2

0

Promises are used as handles to asynchronous code. You can later use this (as a variable name) to check the success.

Docs say:

A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.

Also read:

$http

$q

0xc0de
  • 8,028
  • 5
  • 49
  • 75
0

Promises are used to make code more readable, better organized (avoid spaghetti code), and more flexible.

However, that example you have there is using a bad technique known as the "deferred antipattern". A better way to accomplish the same thing would be:

var list = function (params) {
    if (!params) {
        params = {};
    }
    if (params.q) {
        params.q = JSON.stringify(params.q);
    }

    return $http.get(someurl, {params: params}).then(function (result) {
        return result.data;
    });
};
Community
  • 1
  • 1
JLRishe
  • 99,490
  • 19
  • 131
  • 169