Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function with type 'T -> Async<'T> like C#'s Task.FromResult

I'm playing around asynchronous programming and was wondering if there's a function that exists that can take a value of type 'T and transform it to an Async<'T>, similar to C#'s Task.FromResult that can take a value of type TResult and transform it to a Task<TResult> that can then be awaited.

If such a function does not exist in F#, is it possible to create it? I can kind of emulate this by using Async.AwaitTask and Task.FromResult, but can I do this by only using Async?

Essentially, I'd like to be able to do something like this:

let asyncValue = toAsync 3 // toAsync: 'T -> Async<'T>

let foo = async{      
  let! value = asyncValue
}
like image 999
Ghi102 Avatar asked Apr 19 '18 17:04

Ghi102


1 Answers

...or just async.Return

let toAsync = async.Return
let toAsync` x = async.Return x

moreover there is async.Bind (in tupled form)

let asyncBind 
    (asyncValue: Async<'a>) 
    (asyncFun: 'a -> Async<'b>) : Async<'b> = 
    async.Bind(asyncValue, asyncFun)

you could use them to make pretty complicated async computation without builder gist link

let inline (>>-) x f = async.Bind(x, f >> async.Return)

let requestMasterAsync limit urls =
    let results = Array.zeroCreate (List.length urls)
    let chunks =
        urls
        |> Seq.chunkBySize limit
        |> Seq.indexed
    async.For (chunks, fun (i, chunk) -> 
        chunk 
        |>  Seq.map asyncMockup 
        |>  Async.Parallel
        >>- Seq.iteri (fun j r -> results.[i*limit+j]<-r))
    >>- fun _ -> results
like image 82
Szer Avatar answered Oct 16 '22 18:10

Szer