[AngularJS] Promise

Promise : Asynchronous call

Basic HTTP get call

$http.get('/whatever').success(function(data) {
...
});

NOTE : $http.get return HttpPromise which contains success(), error() method

Handle Promise using then()

$http.get('/whatever').then(function(response) {
response.data; //
});

NOTE : then() return a new promise

To catch error of then()

.then(function(){ }).catch(function() {
// error message here
});

or passing 2 function, since

.then(function(){
// success
},
function(){
// error
})

Using $q, instead of HttpPromise

var getPoneys = function() {
var defer = $q.defer();

$http.get('/api/poneys').then(function(response) {
defer.resolve(response.data);
}, function(response) {
defer.reject(response);
});

return defer.promise;
};

ref : http://blog.ninja-squad.com/2015/05/28/angularjs-promises/

jQuery also have var d = $.Deferred();

d.resolve(obj);

d.isResolved()

d.promise();

when()

$q.when(object).then(function(object){});

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s