简体   繁体   English

如何在 F# 中使用 Async 和 AsyncResult

[英]how to use Async with AsyncResult in F#

Using the FsToolkit.ErrorHandling library, let's take an example:使用 FsToolkit.ErrorHandling 库,我们举个例子:

let doStuff =
    result {
        let! x = doSomething "hello"
        let! y = doAnotherthing "world"
        let  z = combineTwo x y
        return z
    }

now, I have an async version of combinedTwo called combinedTwoAsync:现在,我有一个名为 combineTwoAsync 的 combineTwo 的异步版本:

let doStuff =
    result {
        let! x = doSomething "hello"
        let! y = doAnotherthing "world"
        let  z = combineTwoAsync x y |> Async.AwaitTask |> Async.RunSynchronously
        return z
    }

but I saw that they have an asyncResult expression which returns an Async<Result<'a, 'b>> type但我看到他们有一个 asyncResult 表达式,它返回一个 Async<Result<'a, 'b>> 类型

however, I can't do something like:但是,我不能这样做:

let doStuff =
    asyncResult {
        let! x = doSomething "hello"
        let! y = doAnotherthing "world"
        let! z = combineTwoAsync x y
        return z
    }

since doSomethingAsync is just an async function that doesn't return a Result object因为 doSomethingAsync 只是一个不返回结果 object 的异步 function

I guess this was planned with the idea that all async functions would return an Async<Result<>> type, but I'm trying to figure out how to use async calls (which are to external libs) within a result computation expression to return an Async<Result<>>..我想这是计划的,所有异步函数都将返回 Async<Result<>> 类型,但我试图弄清楚如何在结果计算表达式中使用异步调用(对外部库)返回一个异步<Result<>>..

hopefully this makes some sense:)希望这是有道理的:)

In general, for functors (of which async is one), one could use map to apply some sort of transformation to the functor's value, such as wrapping it in a Result.Ok , for example:一般来说,对于函子(其中async是其中之一),可以使用map对函子的值进行某种转换,例如将其包装在Result.Ok中,例如:

// xAsyncResult : Async<Result<_,_>>
let xAsyncResult = doSomething "hello" |> Async.map Result.Ok

Surprisingly, Async.map is a not a thing.令人惊讶的是, Async.map不是一个东西。 There's even an issue about it .甚至还有一个问题

But no matter: it's easy enough to implement:但没关系:它很容易实现:

module Async =
  map f a = async {
    let! x = a
    return f a
  }

And then:接着:

let doStuff =
    asyncResult {
        let! x = doSomething "hello" |> Async.map Result.Ok
        let! y = doAnotherthing "world" |> Async.map Result.Ok
        let! z = combineTwoAsync x y
        return z
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM