35 people like it.

Simple asynchronous functions

The snippet demonstrates how to compose simple asynchronous functions and how to use try .. with to handle exceptions in asynchronous workflows.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
// Simple asynchronous function that capitalizes a string
let capitalizeAsync (s:string) = async {
  return s.ToUpper() }

// Simple asynchronous function that appends "Hello" to front
let addHello (s:string) = async {
  return "Hello " + s + "!" }

// Asynchronous function that calls two other asynchronous 
// functions asynchronously and uses 'try .. with' to 
// handle exceptions that may occur in a standard way
let processWord (s:string) = async {
  try
    let! cap = capitalizeAsync(s)
    let! hcap = addHello(cap)
    return hcap
  with e ->
    return "Exception occurred!" }
val capitalizeAsync : s:string -> Async<string>

Full name: Script.capitalizeAsync
val s : string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
val async : AsyncBuilder

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.async
System.String.ToUpper() : string
System.String.ToUpper(culture: System.Globalization.CultureInfo) : string
val addHello : s:string -> Async<string>

Full name: Script.addHello
val processWord : s:string -> Async<string>

Full name: Script.processWord
val cap : string
val hcap : string
val e : exn
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/3q
Posted:13 years ago
Author:Tomas Petricek
Tags: async , asynchronous , workflows , try , exception