raganwald/allong.es — pull request #13 by wizardwerdna (2013-04-19 22:05:10+00:00)
Title: Pretty pretty promises... a refactoring

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

```javascript
return promiseIn.then((function(value) {
return fnReturningAPromise(value).then(resolvePromiseOut, rejectPromiseOut);
}), rejectPromiseOut);
```
with the more elegant, but mind-bending:

```javascript
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.