Created
March 6, 2024 17:20
-
-
Save ninjarobot/84ba504c3bc78e0b690bf6dc9c5820ca to your computer and use it in GitHub Desktop.
F# async composition
This file contains hidden or 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
let sleepOnError fn = | |
async { | |
let! (res:Result<_,_>) = fn | |
return! | |
match res with | |
| Ok o -> async.Return (Ok o) | |
| Error e -> | |
async { | |
do! Async.Sleep 750 | |
return Error e | |
} | |
} | |
let retryOnError fn = | |
async { | |
let! (res:Result<_,_>) = fn | |
return! | |
match res with | |
| Ok o -> async.Return (Ok o) | |
| Error e -> | |
fn | |
} | |
let sleepAndRetryOnError = sleepOnError >> retryOnError | |
let sleepAndRetryTwiceOnError = sleepAndRetryOnError >> sleepAndRetryOnError | |
let someFun (s:string) = | |
async { | |
if System.DateTime.Now.Second % 2 = 0 then | |
eprintfn "Got an error" | |
return Error "Some error" | |
else | |
return Ok $"Running {s} in someFun" | |
} | |
(someFun "someFun") |> sleepAndRetryTwiceOnError |> Async.RunSynchronously |> printfn "%A" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment