raganwald / allong.es

https://leanpub.com/javascriptallongesix
484 stars 28 forks source link

Pretty pretty promises... a refactoring #13

Closed wizardwerdna closed 11 years ago

wizardwerdna commented 11 years ago

The attached pull request suggests a nuanced, but elegant refactoring of sequence.Then, replacing the tricky to read:

return promiseIn.then((function(value) {
   return fnReturningAPromise(value).then(resolvePromiseOut, rejectPromiseOut);
}), rejectPromiseOut);

with the more elegant, but mind-bending:

return promiseIn
            .then(fnReturningAPromise, rejectPromiseOut)
            .then(resolvePromiseOut, rejectPromiseOut)

This identity arises from the semantics of the promise.then operation. Indeed, with due attention to a closing base case (a known settled promise), it is possible to define a promises '.then' implementation as a recursive call to .then(...).then(...). (I think I first saw the germ of this in Brian's code for avow.) Bending my brain around this as I was coding my Covenant library, was the first stage of enlightenment to "getting" promise semantics.

In view of your contributions to elegance in coding, I thought you would want yours to show off this lovely identity. Not sure enough about monads and gonads to assure that it is what you want, but it seems right from the code and does pass your tests. And thanks for the library, I shamelessly stole "once" to get Covenant passing the Promises/A+ 1.1 suite.