Hacker News new | ask | show | jobs
by masklinn 5183 days ago
> Besides just plain futures, the join and chainify abstractions from the futures library I linked allow you to create really nice code.

jQuery's deferreds also provide these tools (or their utility would be far more limited). Join is available through `$.when` and noted in the article:

    $.when(fn1(), fn2()).then(op)
will only execute `op` when both `fn1()` and `fn2()`'s results resolve, and sequences are available through `$.Deferred.pipe`: `pipe` creates a new Deferred which by default is just a proxy for the one it was called on but

* If the executed handler[0] returns a value, this value replaces the value #pipe's source was resolved or rejected with, e.g.

    var d = $.Deferred(),
        r = d.pipe(function (val) { return val / 2; });
    d.resolve(42);

    d.then(function (val) { /* val will be 42 */ });
    r.then(function (val) { /* val will be 42 / 2 -> 21 */ });
* If the executed handler returns a Deferred, that deferred will replace the original one, which allows both chaining deferred (executing a second async operation following the first one) and inverting results (#pipe allows — conditionally or not — transforming a rejection into a resolution and a resolution into a rejection, this is useful when there are multiple ways to get a value so that the second one can be tried iif the first one fails)

[0] like #then, #pipe can take both a success and a failure handler