"A promise represents the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its then method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled."
$resource('http://api.blah.com').query(function(data) {
doSomethingWith(data);
});
What if doSomethingWith() is also async?
$resource('http://api.blah.com').query(function(data) {
doSomethingWith(data, function(newData) {
doSomethingElseWith(newData);
});
});
What about errors?
$resource('http://api.blah.com').query(function(data) {
doSomethingWith(data, function(newData) {
doSomethingElseWith(newData);
}, function(otherError) {
handleError(otherError);
});
}, function(error) {
handleError(error);
});
Every promise then() returns a new promise,
so they are chainable
$resource('http://api.blah.com').query().then(
function(data) {
return doSomethingWith(data);
}).then(function(newData) {
doSomethingElseWith(newData);
});
Can reject any promise in the chain
and propagate the error
$resource('http://api.blah.com').query().then(
function(data) {
return doSomethingWith(data);
}).then(function(newData) {
doSomethingElseWith(newData);
}, function(error) {
handleError(error);
});
function doSomethingWith(data) {
var deferred = $q.defer(); if (data.length > 0) { deferred.resolve(data); } else { deferred.reject('empty data!'); } return deferred.promise; }
deferred.promise:
http://github.com/smathson/ngtest
http://slid.es/scottmathson/
a_quick_intro_to_promises_in_angularjs
Email: smathson@gmail.com
Twitter: @smathson