我有一个有条件地调用异步任务的方法:
let processMsg (msg : SocketMessage) =
task{
//....
//....
let user =
if msg.User.IsSpecified && (msg.User.Value :? IUser) then
user.Value :?> IUser
else
//Compiler: This construct may only be used within a computation expression
let! user' = rest.GetUserAsync(UserId, config.restOptions)
user'
//....
//....
}
编译器提示我必须在计算表达式内。我以为我是。我让它工作的唯一方法是将其拆分为异步子方法:
let getUserAsync (user : SocketUser) =
task{
if user.IsSpecified && (user.Value :? IUser) then
return user.Value :?> IUser
else
let! user' =
rest.GetUserAsync(UserId, config.restOptions)
return (user' :> IUser)
}
现在我有一个额外的异步上下文来处理罕见的极端情况。有没有更好的方法来处理这个问题?
最佳答案
let user = ...
的内部是不是计算表达式。 let
它本身位于计算表达式内部,但其内部的任何内容都不是。所以你不能使用let!
在那里。
做你想做的事情的方法是将其变成 let
进入let!
然后确保其右侧是 Task
:
let! user =
if msg.User.IsSpecified && (msg.User.Value :? IUser) then
Task.FromResult(user.Value :?> IUser)
else
rest.GetUserAsync(UserId, config.restOptions)
关于asynchronous - F# 异步条件分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64861689/