Last active
October 15, 2018 18:06
-
-
Save dbrattli/fb9556fad135c850dc213ac01a97a7ba to your computer and use it in GitHub Desktop.
Promise with Scheduler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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