Transforms the value and state of a Task.
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 e, v1, v2:
(Task e v1).((v1) => Task e v2) => Task e v2
Transforms the value and state of a Task.
As with .map()
the transformation only happens if the original task resolves successfully, but instead of incorporating just the value, .chain()
assimilates the value and state of the returned Task. This allows .chain()
to be used for sequencing computations involving Task.
const { of, rejected } = require('folktale/concurrency/task');
const helloWorld = of('hello').chain(v => of(v + ' world'));
const result1 = await helloWorld.run().promise();
$ASSERT(result1 == 'hello world');
const world = of('hello').chain(v => rejected('world'));
try {
const result2 = await world.run().promise();
throw 'never happens';
} catch (error) {
$ASSERT(error == 'world');
}
const hello = rejected('hello').chain(v => of('world'));
try {
const result3 = await hello.run().promise();
throw 'never happens';
} catch (error) {
$ASSERT(error == 'hello');
}
chain(transformation) {
return new Task(resolver => {
const execution = this.run();
resolver.onCancelled(() => execution.cancel());
execution.listen({
onCancelled: resolver.cancel,
onRejected: resolver.reject,
onResolved: value => {
execution.link(transformation(value).run().listen({
onCancelled: resolver.cancel,
onRejected: resolver.reject,
onResolved: resolver.resolve
}));
}
});
});
}