I'm already using Option / Either types from fp-ts in my project and now I'm looking for cancellable promise library, so I've decided to consider fp-ts Task for that purpose, but I have not found information whether Task cancellable or not in docs. Is there way to cancel Tasks? Also I'm looking for analog of Promise.all function for Tasks.
Is there way to cancel Tasks?
No, Task<A> is basically () => Promise<A>.
AFAIK the following implementations are cancellable
Fluture (https://github.com/fluture-js/Fluture)IO (https://funfix.org/api/effect/)I'm looking for analog of Promise.all
That's sequence (from Traversable)
import { task } from 'fp-ts/lib/Task'
import { array } from 'fp-ts/lib/Array'
import { sequence } from 'fp-ts/lib/Traversable'
// sequenceTasks: <A>(tfa: Task<A>[]) => Task<A[]>
const sequenceTasks = sequence(task, array)
Thanks for response.
@axin You can also try Apply's sequenceT
@gcanti sequence guarantees the order of the promises?
@AlexRex it depends on the involved instances (of Traversable and Applicative). What do you mean by "order of the promises"?
So, let's say we have a function which returns a promise. Then we have an array of elements which we need to apply that function, but we want to keep the order of the resolving promises, so, a promise waits for the result of the previous promise.
So basically would be like doing the following:
import { Task } from 'fp-ts/lib/Task';
const names = ['Gcanti', 'AlexRex'];
const waitAndSayName = (name: string) => {
return new Task(() => new Promise((resolve) => {
setTimeout(() => {
resolve(name);
}, Math.random() * 1000);
}));
};
waitAndSayName(names[0]).chain(() => waitAndSayName(names[1])).run();
I tried array.traverse and sequence but all promises run in parallel instead of running in serie.
Ok, you can control the behaviour by tweaking the Applicative instance
import { array } from 'fp-ts/lib/Array'
import { task, taskSeq } from 'fp-ts/lib/Task'
// parallel
array
.traverse(task)(names, waitAndSayName)
.run()
// sequential
array
.traverse(taskSeq)(names, waitAndSayName)
.run()
I think these are important use cases, so I have documented them here: https://github.com/gcanti/fp-ts/pull/833/commits/fd1a74e53a6efb5f0bb603fa6e057dff326d50f0 This is soon ready to be merged, so I'll close this issue.
Most helpful comment
Ok, you can control the behaviour by tweaking the
Applicativeinstance