This is something I encountered recently on a project. I was working with a system that required short-lived server generated tokens to be passed back with every request, for authorisation. The immediate (and rather naive) idea of implementing a service for this comes out something like:

Service.prototype.getToken = function (username, password) {
    return http.post(this.url + '/Auth',
                      { user: username,
                        password: password });
}
Service.prototype.productDetails (creds, id) {
    return this.getToken(creds.user, creds.password)
                .then(function (token) {
                    // now request the product details
                });
}

Unfortunately, it's not that easy, as the astute reader will have realised. Since the second request to get the product details is also asynchronous, we can't chain the promises this simply, we need to return the second promise—the nested one. To achieve this an explicit deferred object is required:

var deferred = Q.defer();

this.getToken(creds.user, creds.password).done(function (token) {
    http.post(this.url + '/Product/' + id, { Authorisation: token })
        .done(deferred.resolve, deferred.reject);
}, deferred.reject);

return deferred.promise;

Great, this works! It's not, however, the most elegant code, it's also going to get rather repetitive if every service call must follow this pattern; for this reason, it would be nice to extract out this awkward chaining of dependant promises, to implement true promise composition. Composition is the act of combining two (or more) things into one. I tend to borrow a signature from category theory (via Haskell) when considering composing behaviours:

(>>=) :: Monad m => m a -> (a -> m b) -> m b

This is a very generic function called bind that is responsible for a great deal of composition in functional programming. When made specific for composing promises:

// bindAsync :: Promise a -> (a -> Promise b) -> Promise b
function bindAsync (promise, func) {
    var deferred = Q.defer();

    promise.done(function (result) {
        func(result).done(deferred.resolve, deferred.reject);
    }, deferred.reject);

    return deferred.promise;
}

With this nice little function, it's possible to write much more terse chained promises. Still thinking functionally, I'll remove the call to getToken in getProductDetails and give the burden of their composition to any caller.

Service.prototype.getToken = function (username, password) {
    return http.post(this.url + '/Auth',
                      { user: username,
                        password: password });
}
Service.prototype.productDetails (id, token) {
    return http.post(this.url + '/Product/' + id, { Authorisation: token });
}

A hypothetical caller might look like:

function productDetails (id) {
    return bindAsync(service.getToken(user, pass),
                     service.productDetails.bind(this, id));
}