Proper way to skip a then function in Q Promises

It depends a bit on what the conditions to skip are, what kind of operations you are doing, and how “useful” the whole thing is when the conditions failed. You might be able to use a smart rejection here to bring the message across. Otherwise, I believe the correct way to deal with this is really a nested set of promise calls.

This also matches the core idea behind promises, which is to bring back synchronous control structures to asynchronous code execution. In general, when using promises, you should first think about how you would do the task with synchronous code. And if you think about your situation, it would probably work like this:

var contents = readFromFile();
var results = initialOperation(contents);
if (fancyCondition(results)) {
     results = doSomething(results);
     results = doMore(results);
}
processAndPrint(results);

So you would have a real branch in there in synchronous code. As such, it makes no sense that you would want to avoid that in asynchronous code using promises. If you could just skip things, you were essentially using jumps with gotos. But instead, you branch off and do some other things separately.

So going back to promises and asynchronous code, having an actual branch with another set of chained operations is completely fine, and actual in spirit of the intent behind promises. So above code could look like this:

readFromFile(fileName)
.then(initialOperation)
.then(function (results) {
    if (fancyCondition(results) {
        return doSomething(results)
            .then(doMore);
    }
    return results;
})
.catch(errorHandler)
.then(processResults)
.then(outputResults); // Or `done` in Q

Also note, that the promise pipeline automatically looks a lot more cleaner when you start using functions that return promises on their own, instead of creating them inline from then.

Leave a Comment