AngularJS Deferring operations using $q.defer


Example

We can use $q to defer operations to the future while having a pending promise object at the present, by using $q.defer we create a promise that will either resolve or reject in the future.

This method is not equivalent of using the $q constructor, as we use $q.defer to promisify an existing routine that may or may not return (or had ever returned) a promise at all.

Example:

var runAnimation = function(animation, duration) {
    var deferred = $q.defer();
    try {
        ...
        // run some animation for a given duration
        deferred.resolve("done");
    } catch (err) {
        // in case of error we would want to run the error hander of .then
        deferred.reject(err);
    }
    return deferred.promise;
}

// and then
runAnimation.then(function(status) {}, function(error) {})

  1. Be sure you always return a the deferred.promise object or risk an error when invoking .then

  2. Make sure you always resolve or reject your deferred object or .then may not run and you risk a memory leak