F#的异步工作流程的Scala等价物是什么?
例如,如何跟随F#片段转换为惯用的Scala?
open System.Net
open Microsoft.FSharp.Control.WebExtensions
let urlList = [ "Microsoft.com", "http://www.microsoft.com/"
"MSDN", "http://msdn.microsoft.com/"
"Bing", "http://www.bing.com"
]
let fetchAsync(name, url:string) =
async {
try
let uri = new System.Uri(url)
let webClient = new WebClient()
let! html = webClient.AsyncDownloadString(uri)
printfn "Read %d characters for %s" html.Length name
with
| ex -> printfn "%s" (ex.Message);
}
let runAll() =
urlList
|> Seq.map fetchAsync
|> Async.Parallel
|> Async.RunSynchronously
|> ignore
runAll()
答案 0 :(得分:6)
您可以使用Futures
将代码更多或更少直接转换为Scala(但丢失了一些重要功能):
import scala.actors.Futures
import Futures._
val urlList = Map("Microsoft.com" -> "http://www.microsoft.com/",
"MSDN" -> "http://msdn.microsoft.com/",
"Bing" -> "http://www.bing.com")
def fetchAsync(name: String, url: String) = future {
// lengthy operation simulation
Thread.sleep(1000)
println("Fetching from %s: %s" format(name, url))
}
def runAll =
//Futures.awaitAll( <- if you want to synchronously wait for the futures to complete
urlList.map{case (name, url) => fetchAsync(name, url)}
//)