Return Data in JavaScript Promises

As I was coding promises in a new module the other day, I wondered if I could return data in my anonymous function passed to then. Previously, it seems like I almost always returned data via resolve (i.e. def.resolve(data);). I probably just overcomplicated things and had too many promises involved. At any rate, I was almost sure what I wanted to do would work, but to test it in isolation I wrote up the functions below.

function createPromise(data) {
    return Q(data);
}
 
function doSomething() {
    var otherData = [1, 2, 3];
    return createPromise(['a', 'b', 'c'])
        .then(function (data) {
            console.log(data); //['a', 'b', 'c']
            return otherData;
        });
}
 
function doSomethingMore() {
    console.log('start');
    return doSomething()
        .then(function (otherData) {
            console.log(otherData); //[1, 2, 3]
            console.log('finish');
        });
}
 
doSomethingMore();

Some explanation and observations:

First. If you were unaware, calling Q(value) where value is not a promise returns a fulfilled promise with value.

Second. The createPromise function isn’t really necessary. I could just as easily substitute createPromise() in doSomething with Q(['a', 'b', 'c']). However, functions are often a bit more complex and I wanted the example to illustrate that this could very well involve 3 separate functions.

Third. then returns a promise such that promise2 = promise1.then(onFulfilled, onRejected, onProgress). promise2 is not fulfilled until the appropriate onFulfilled or onRejected function has finished running.

Fourth. You could just as easily nest a function that returns promise3 and promise2 would not resolve until promise3 had been fulfilled or rejected. For example:

function doSomething() {
    var otherData = [1, 2, 3];
    return createPromise(['a', 'b', 'c'])
        .then(function (data) {
            console.log(data);
            return createPromise(otherData);
        });
}

Most of these details (if not all) are explained in the Q API documentation. Take a gander.

JSFiddle if you like.

Comments, questions and feedback welcome.