A QUICK INTRO TO
PROMISES IN ANGULARJS

WHAT ARE PROMISES?

Pattern for handling asynchronous operations

"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."

CALLBACK PATTERN

$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);
});

PROMISE PATTERN

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);
  });

PROMISES IN ANGULAR

$q service
 function doSomethingWith(data) {  var deferred = $q.defer();

  if (data.length > 0) {
    deferred.resolve(data);
  } else {
    deferred.reject('empty data!');
  }

  return deferred.promise;
}

deferred.promise:

  • then(successCallback, errorCallback, notifyCallback)
  • catch(errorCallback) - alias for then(null. errorCallback)
  • finally(callback) - always called, regardless of rejection


MORE READING


QUESTIONS?

http://github.com/smathson/ngtest

http://slid.es/scottmathson/
a_quick_intro_to_promises_in_angularjs


http://smathson.github.io

Email: smathson@gmail.com
Twitter: @smathson

a quick intro to promises in angularjs

By Scott Mathson

a quick intro to promises in angularjs

  • 6,004