将同步函数转换为async got"此结构只能在计算表达式中使用"?

时间:2018-06-07 21:02:53

标签: f#

如何将以下代码转换为异步代码?

[I-LOC([u'\u0627\u0644\u0647\u0646\u062f\u064a\u0629'])]

以下内容会出错。

let m1 x = x * 2
let m2 s =
    let l = [1..10]
    l |> List.iter(fun x -> printfn "%d" (m1 x))
    s // the function returns something

以下内容将消除错误,但同步调用let n1 x = async { return x * 2 } let n2 s = async { let l = [1..10] // l will be generated by s l |> List.iter(fun x -> let y = do! n1 x // ERROR: This construct may only be used within computation expressions printfn "%d" y) return s }

n1

let n2 s = async { let l = [1..10] l |> List.iter(fun x -> async { let! y = n1 x printfn "%d" y } |> Async.RunSynchronously) return s } 将在另一个函数的n2中调用。所以在最外层,我想为列表做List.iter

1 个答案:

答案 0 :(得分:3)

您可以使用for .. in .. do表达式:

let n1 x = async { return x * 2 }
let n2 s =
    async {
        let l = [1..10] // l will be generated by s
        for x in l do
            let! y = n1 x
            printfn "%d" y
        return s
    }