pacta
This is an implementation of algebraic Promises in
node.js having been convinced by James
Coglan
and Aanand Prasad.
Pacta's promises can be used as the following algebraic structures:
- Semigroups (through
Promise#concat
which concatenates promises containing semigroups such as
arrays and strings); - Monoids (through
Promise#empty
which returns an empty version of a promise that contains a
monoid); - Functors (through
Promise#map
); - Applicative
(through
Promise#ap
and Promise.of
); - Chains (through
Promise#chain
); - Monads (through all of
the above).
Above that, Pacta also provides:
conjoin
to concatenate promises into a list of values regardless of their
original type meaning that non-Monoid types can be combined with others
(e.g. a promise of 'foo'
can be conjoined with [1, 2]
to produce
['foo', 1, 2]
);combine
to conjoin promises without flattening lists (e.g. combining a
promise of [1, 2]
and [3]
will give a promise of [[1, 2], [3]]
instead
of [1, 2, 3]
as it would with concat
and conjoin
);explode
to map over a promise's value but, instead of receiving a single
value, explode the promise's value into seperate arguments:
Promise.of([1, 2]).explode(function (x, y) {
console.log(x);
console.log(y);
});
It also defines a monoid interface for Array
and String
, implementing
empty
such that:
Array.empty();
String.empty();
Note that Pacta does not handle errors or the concept of a failed promise as
yet.
See the HTTP client
example and
the test
suite for more
information.
Usage
var Promise = require('pacta').Promise;
var p = new Promise();
setTimeout(function () {
p.resolve('Foo');
}, 1000);
p.map(console.log);
p.map(function (x) {
return x + '!';
}).map(console.log);
var p2 = new Promise();
setTimeout(function () {
p2.resolve(['bar']);
}, 500);
var p3 = Promise.of(['baz']);
p2.concat(p3).map(function (x) {
console.log(x);
});
p.conjoin(p2).map(function (x) {
console.log(x);
});
p.combine(p2).map(function (x) {
console.log(x);
});
p.combine(p2).explode(function (x, y) {
console.log(x);
console.log(y);
});