Documentation
¶
Overview ¶
Package async provides implementation of useful Golang asynchronous patterns.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Promise ¶ added in v0.0.2
Promise is a function returned by async.Execute function. It can be called later to retrieve result of asynchronous execution.
func Execute ¶
Execute function f asynchronously. Returns promise which can be called to retrieve function's f result. Calling promise will block execution until function f returns. It is advisable to use context to cancel function's f execution (see example code).
Example ¶
package main
import (
"fmt"
"dexm.lol/async"
)
func main() {
promise := async.Execute(func() (string, error) {
// Perform some lengthy operation.
return "string result of some lengthy operation", nil
})
// Perform another lengthy operation.
res, err := promise()
fmt.Println("Result:", res)
fmt.Println("Error:", err)
}
Output: Result: string result of some lengthy operation Error: <nil>
Example (Context) ¶
package main
import (
"context"
"fmt"
"net/http"
"dexm.lol/async"
)
func main() {
// Cancel context when main function exits to signal asynchronous function to exit as well.
ctx, cancel := context.WithCancel(context.TODO())
defer cancel()
promise := async.Execute(func() (string, error) {
// Use context to cancel asynchronous function if base function exits early.
_, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com/", nil)
if err != nil {
return "", err
}
return "request was successful", nil
})
_, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.com/", nil)
if err != nil {
// It is safe to exit this function early, context will abort asynchronous function.
return
}
res, err := promise()
fmt.Println("Result:", res)
fmt.Println("Error:", err)
}
Output: Result: request was successful Error: <nil>
Example (WaitGroups) ¶
package main
import (
"fmt"
"sync"
"dexm.lol/async"
)
func main() {
// Use wait groups to execute multiple asynchronous functions and read results only when all of them succeeded.
var wg sync.WaitGroup
wg.Add(2)
promise1 := async.Execute(func() (string, error) {
defer wg.Done()
return "string result", nil
})
promise2 := async.Execute(func() (int, error) {
defer wg.Done()
return 42, nil
})
// Wait for both asynchronous function to complete before getting results.
wg.Wait()
stringRes, err := promise1()
fmt.Printf("Result of 1st asynchronous function: %s. Error: %v\n", stringRes, err)
intRes, err := promise2()
fmt.Printf("Result of 2nd asynchronous function: %d. Error: %v\n", intRes, err)
}
Output: Result of 1st asynchronous function: string result. Error: <nil> Result of 2nd asynchronous function: 42. Error: <nil>
Click to show internal directories.
Click to hide internal directories.