Chooses and executes a function for each variant in a Task. The function must return a new task, whose value and state will be assimilated.
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 e1, e2, v1, v2:
type Pattern = { row |
Cancelled: () => Task e2 v2,
Resolved: (b) => Task e2 v2,
Rejected: (a) => Task e2 v2
}
(Task e1 v1).(Pattern) => Task e2 v2
Chooses and executes a function for each variant in a Task. The function must return a new task, whose value and state will be assimilated.
const { task, of, rejected } = require('folktale/concurrency/task');
const result1 = await of('hello').willMatchWith({
Cancelled: () => of('cancelled'),
Rejected: (error) => of(`rejected ${error}`),
Resolved: (value) => of(`resolved ${value}`)
}).run().promise();
$ASSERT(result1 == 'resolved hello');
const result2 = await rejected('hello').willMatchWith({
Cancelled: () => of('cancelled'),
Rejected: (error) => of(`rejected ${error}`),
Resolved: (value) => of(`resolved ${value}`)
}).run().promise();
$ASSERT(result2 == 'rejected hello');
const result3 = await task(r => r.cancel()).willMatchWith({
Cancelled: () => of('cancelled'),
Rejected: (error) => of(`rejected ${error}`),
Resolved: (value) => of(`resolved ${value}`)
}).run().promise();
$ASSERT(result3 == 'cancelled');
willMatchWith(pattern) {
return new Task(resolver => {
const execution = this.run();
resolver.onCancelled(() => execution.cancel());
const resolve = (handler) => (value) => handler(value).run().listen({
onCancelled: resolver.cancel,
onRejected: resolver.reject,
onResolved: resolver.resolve
});
execution.listen({
onCancelled: resolve(_ => pattern.Cancelled()),
onRejected: resolve(pattern.Rejected),
onResolved: resolve(pattern.Resolved)
});
});
}