Skip to content

Instantly share code, notes, and snippets.

@ninjarobot
Created March 6, 2024 17:20
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 ninjarobot/84ba504c3bc78e0b690bf6dc9c5820ca to your computer and use it in GitHub Desktop.
Save ninjarobot/84ba504c3bc78e0b690bf6dc9c5820ca to your computer and use it in GitHub Desktop.
F# async composition
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