F#异步方法_GetPort返回Async<unit>而非Async<Port>类型不匹配问题
问题原因
- 多余的
do关键字:你在| None ->分支后添加了do关键字,该关键字用于标记无返回值的副作用执行块,要求后续所有表达式返回unit类型。这导致编译器直接推断整个match表达式为unit类型,整个异步块的返回值被判定为Async<unit>,和你声明的Async<Port>类型不匹配。 - 缺少显式返回声明:F#的
async {}计算表达式要求使用return关键字显式返回最终值,单独书写变量名会被识别为丢弃该值,表达式最终返回unit。 - 递归调用写法冗余:原代码中先通过
let!接收递归调用的结果再返回,属于不必要的写法,可以直接用return!直接传递异步操作的返回结果。
修复代码
member this.GetPort(): Async<Port> = this._GetPort(DateTime.Now) member this._GetPort(startTime: DateTime): Async<Port> = async { match this._TryGetOpenPort() with | Some(port) -> return port | None -> if (DateTime.Now - startTime).TotalMinutes >= 5 then raise (Exception "Unable to open a port") else do! Async.Sleep(100) return! this._GetPort(startTime) } member this._TryGetOpenPort(): Option<Port> = // 原有逻辑保持不变
内容的提问来源于stack exchange,提问作者Maurdekye
相关产品推荐
相关产品推荐

