【问题标题】:Combining F# async functions结合 F# 异步函数
【发布时间】:2011-04-17 11:37:19
【问题描述】:

我在这里有点沮丧。我知道我有所有的东西,但我不知道如何组合它们......

let saveImageToDisk path content =
    async {
        use s = new FileStream(path, FileMode.OpenOrCreate)
        do! s.AsyncWrite(content)
        printfn "Done writing %A" path
        } // returns Async<unit>

let getImages imageUrls =
    imageUrls
        |> Seq.map (fun url -> topath url, getImage url)
        //Next line not happy because content is Async<byte[]> instead of byte[]
        |> Seq.map (fun (path, content) -> saveImageToDisk path content)
        |> Async.Parallel
        |> Async.RunSynchronously

【问题讨论】:

    标签: asynchronous f#


    【解决方案1】:

    您可以使用async 表达式将两者结合起来:

    let getImages imageUrls =
        imageUrls
            |> Seq.map (fun url -> async {
                  let! content = getImage url
                  return! saveImageToDisk (topath url) content })
            |> Async.Parallel
            |> Async.RunSynchronously
    

    【讨论】:

    • 基本上,由于 Async 是一个 monad,因此您可以将它们组合到另一个 Async 中。 :)
    猜你喜欢
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多