Skip to content

Instantly share code, notes, and snippets.

@rpominov
Created May 22, 2016 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpominov/9b4e3f858b35905e66465211f783dc13 to your computer and use it in GitHub Desktop.
Save rpominov/9b4e3f858b35905e66465211f783dc13 to your computer and use it in GitHub Desktop.
Task concept
type Result<L,R> =
| {T: 'Right', value: R}
| {T: 'Left', value: L}
| {T: 'Thrown', error: any}
| {T: 'Cancel'}
type Cancel = () => void
type RunHandler<L,R> =
| (result: Result<L,R>) => void
| {
Right?: (value: R) => void,
Left?: (value: L) => void,
Thrown?: (error: any) => void,
Cancel?: () => void,
}
type RunOptions = {
catch?: boolean
}
type Task<L,R> = {
run(handler: RunHandler<L,R>, options?: RunOptions): Cancel
}
@rpominov
Copy link
Author

Features

  • Cancelation (Rx/basic-streams like)
  • Optional exceptions catching (recommended usage: catch:false in browser, catch:true on server)
  • Exceptions are distinguished from Left

@rpominov
Copy link
Author

rpominov commented May 28, 2016

Alternative approach 1

  • Instead of making it Task<Result<L,R,E>> internally make it just Task<A>
  • Users can wrap an Either<L,R> into Task<A> by themselves
  • Additionally provide a runAndCatch(onSuccess, onError) that uses different from run strategy and wraps everything to try..catch stopping on first exception and calling onError with it, or calling onSuccess as normal run(onSuccess) if no exceptions appeared
  • Note: with runAndCatch we will not have an ability to recover, there no chainError(). Or we could actually have chainError() but this is probably bad idea...

In browser you would use run() and on the server you would use runAndCatch() all the rest of the code should be universal and dealing with Task<A> type, using Task<Either<L,R>> if necessary.

@rpominov
Copy link
Author

rpominov commented May 29, 2016

Alt 2

Like #1 but with Task<L,R>. L and R only for user's explicit "lefts" / "rights", catched exceptions never go there. Exceptions still go only into onError callback in runAndCatch and can't be recovered from etc.

And yeah, we don't need onCancel callback probably...

@rpominov
Copy link
Author

Alt 3

Like #2 but catched exceptions go into L.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment