我正在玩异步编程,并且想知道是否存在可以采用类型'T
的值并将其转换为Async<'T>
的函数,类似于C#的Task.FromResult
可以采用TResult
类型的值并将其转换为可以等待的Task<TResult>
。
如果F#中不存在这样的功能,是否可以创建它?我可以通过使用Async.AwaitTask和Task.FromResult来模拟这个,但是我可以通过仅使用Async来实现吗?
基本上,我希望能够做到这样的事情:
let asyncValue = toAsync 3 // toAsync: 'T -> Async<'T>
let foo = async{
let! value = asyncValue
}
答案 0 :(得分:7)
您可以在return
表达式中使用async
:
let toAsync x = async { return x }
答案 1 :(得分:6)
...或只是async.Return
let toAsync = async.Return
let toAsync` x = async.Return x
此外还有async.Bind(以tupled形式)
let asyncBind
(asyncValue: Async<'a>)
(asyncFun: 'a -> Async<'b>) : Async<'b> =
async.Bind(asyncValue, asyncFun)
如果没有构建器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