Skip to content

Instantly share code, notes, and snippets.

@dbrattli
Last active October 15, 2018 18: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 dbrattli/fb9556fad135c850dc213ac01a97a7ba to your computer and use it in GitHub Desktop.
Save dbrattli/fb9556fad135c850dc213ac01a97a7ba to your computer and use it in GitHub Desktop.
Promise with Scheduler
type Promise<'a> () =
let mutable result : Result<'a, exn> option = None
let catchCbs = List<Callback<exn>> ()
let thenCbs = List<Callback<'a>> ()
member this.Resolve (value: 'a) =
result <- Some <| Ok value
for cb in thenCbs do
scheduler.Post (fun () -> cb value)
member this.Reject (error : exn) =
result <- Some <| Error error
for cb in catchCbs do
scheduler.Post (fun () -> cb error)
member this.Then<'a> (cb : Callback<'a>) : Promise<'a> =
thenCbs.Add cb
// Replay existing result if any
result
|> Option.map (Result.map (fun value -> scheduler.Post (fun () -> cb value)))
|> ignore
this
// Subscribe OnError
member this.Catch (cb: Callback<exn>) =
catchCbs.Add cb
// Replay existing error if any
result
|> Option.map (Result.mapError (fun error -> scheduler.Post (fun () -> cb error)))
|> ignore
this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment