Dilip B S
Dilip B S

Reputation: 213

Confusion on promise objects

I've read about promise objects and infact have worked on promise objects but still I must say I'm not clear on the basics.

$http.get('/someURL').then(function(response) {
// do something
}, function(error) {
});

People say that .then returns a promise object. In the above example $http.get() returns a promise object. So what does this line mean? Does it mean promise.promise?? (promise object returned by $http.get() dot promise returned by .then)?

Can anyone please clarify?

Upvotes: 0

Views: 78

Answers (2)

NoahC
NoahC

Reputation: 121

One of the cool features of promises is that they can be linked together. The $http.get() returns a promise which you have called the then on. That then also returns a promise and allows you to do additional things in another then statement. For instance:

function myGet() {
    return $http.get('myRoute').then(
        function(res) {
           //do something
           return res;
        }, function(err) {
           return $q.reject(err);
        });  
}

myGet().then(
    function(res) {
        //Do something else
    }, function(err) {
        //Handle Error
    });

This can be very handy if you want to have a procedure happen after the myGet function either is succesful or has an error.

Upvotes: 2

jfriend00
jfriend00

Reputation: 707696

$http.get() returns a promise. You can then call .then() on that promise. .then() returns yet another promise that you aren't actually using in your code.

For example, you could do this:

var p = $http.get('/someURL').then(function(response) {
    // do something
}, function(error) {
    // do something on error
});

// p is a promise
p.then(function() {
    // more code here that runs after the previous code
});

Or, you could do:

$http.get('/someURL').then(function(response) {
    // do something
}, function(error) {
    // do something on error
}).then(function() {
    // more code here
});

So, each .then() handler returns yet another promise so you can chain as many times as you want. One particularly useful feature is that if you return a promise from a .then() handler callback, then the promise that the .then() handler already returned will inherit that promise you return from the callback like this:

$http.get('/someURL').then(function(response) {
    return $http.get('/someOtherURL');
}, function(error) {
    // do something on error
}).then(function(secondResponse) {
    // will get here when both http.get operations are done
});

Upvotes: 4

Related Questions