Limited pattern matching for futures.
This API is still experimental, so it may change or be removed in future versions. You should not rely on it for production applications.
forall a, b, c, d:
type Pattern = { r |
Cancelled: () => Future c d,
Resolved: (b) => Future c d,
Rejected: (a) => Future c d
}
(Future a b).(Pattern) => Future c d
Limited pattern matching for futures.
const { of, rejected } = require('folktale/concurrency/future');
of(1).willMatchWith({
Cancelled: () => of('no'),
Rejected: (x) => of(x + 1),
Resolved: (x) => of(x - 1)
}).listen({
onResolved: (x) => $ASSERT(x == 0)
});
rejected(1).willMatchWith({
Cancelled: () => of('no'),
Rejected: (x) => of(x + 1),
Resolved: (x) => of(x - 1)
}).listen({
onResolved: (x) => $ASSERT(x == 2)
})
willMatchWith(pattern) {
let deferred = new Deferred(); // eslint-disable-line prefer-const
const resolve = (handler) => (value) => handler(value).listen({
onCancelled: () => deferred.cancel(),
onResolved: (newValue) => deferred.resolve(newValue),
onRejected: (reason) => deferred.reject(reason)
});
this.listen({
onCancelled: resolve(pattern.Cancelled),
onResolved: resolve(pattern.Resolved),
onRejected: resolve(pattern.Rejected)
});
return deferred.future();
}