Documentation
¶
Index ¶
- Variables
- func Promisify[T any](fn func() (T, error)) func() *Promise[T]
- func PromisifyWithMgr[T any](mgr *PromiseMgr, fn func() (T, error)) func() *Promise[T]
- func ResetDefaultMgrExecutor(workers int, queueSize int)
- func ResetDefaultMgrMicrotask(workers int, queueSize int)
- type ErrorType
- type Promise
- func All[T any](promises ...*Promise[T]) *Promise[[]T]
- func AllSettled[T any](promises ...*Promise[T]) *Promise[[]Result[T]]
- func Any[T any](promises ...*Promise[T]) *Promise[T]
- func Delay[T any](value T, delay time.Duration) *Promise[T]
- func Map[T any, R any](items []T, fn func(T) *Promise[R]) *Promise[[]R]
- func New[T any](executor func(resolve func(T), reject func(error))) *Promise[T]
- func NewWithMgr[T any](manager *PromiseMgr, executor func(resolve func(T), reject func(error))) *Promise[T]
- func Race[T any](promises ...*Promise[T]) *Promise[T]
- func Reduce[T any, R any](items []T, fn func(R, T) *Promise[R], initial R) *Promise[R]
- func Reject[T any](err error) *Promise[T]
- func Resolve[T any](value T) *Promise[T]
- func Retry[T any](fn func() (T, error), maxRetries int, delay time.Duration) *Promise[T]
- func RetryWithContext[T any](ctx context.Context, fn func() (T, error), maxRetries int, delay time.Duration) *Promise[T]
- func Timeout[T any](promise *Promise[T], timeout time.Duration) *Promise[T]
- func Try[T any](fn func() T) *Promise[T]
- func TryWithError[T any](fn func() (T, error)) *Promise[T]
- func TryWithErrorAndMgr[T any](manager *PromiseMgr, fn func() (T, error)) *Promise[T]
- func TryWithMgr[T any](manager *PromiseMgr, fn func() T) *Promise[T]
- func WithResolvers[T any]() (*Promise[T], func(T), func(error))
- func WithResolversWithMgr[T any](manager *PromiseMgr) (*Promise[T], func(T), func(error))
- func (p *Promise[T]) Await() (T, error)
- func (p *Promise[T]) AwaitWithContext(ctx context.Context) (T, error)
- func (p *Promise[T]) Catch(onRejected func(error) any) *Promise[any]
- func (p *Promise[T]) Finally(onFinally func()) *Promise[T]
- func (p *Promise[T]) IsFulfilled() bool
- func (p *Promise[T]) IsPending() bool
- func (p *Promise[T]) IsRejected() bool
- func (p *Promise[T]) State() State
- func (p *Promise[T]) Then(onFulfilled func(T) any, onRejected func(error) any) *Promise[any]
- type PromiseError
- type PromiseMgr
- func (m *PromiseMgr) Close()
- func (m *PromiseMgr) GetConfig() *PromiseMgrConfig
- func (m *PromiseMgr) IsShutdown() bool
- func (m *PromiseMgr) SetExecutorConfig(workers int, queueSize int) *PromiseMgr
- func (m *PromiseMgr) SetMicrotaskConfig(workers int, queueSize int) *PromiseMgr
- func (m *PromiseMgr) WaitForShutdown()
- type PromiseMgrConfig
- type Result
- type State
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrManagerStopped is returned when trying to use a stopped manager ErrManagerStopped = &PromiseError{ Message: "manager is stopped", Type: ManagerError, } )
Predefined errors for common scenarios
Functions ¶
func Promisify ¶ added in v1.1.4
Promisify converts a function that returns (T, error) to a function that returns *Promise[T] This is the most common pattern in Go where functions return (value, error)
Example ¶
ExamplePromisify demonstrates the Promisify function
// Create a function that returns (string, error) - common Go pattern fetchData := func() (string, error) { return "data from database", nil } // Convert to Promise function promiseFn := Promisify(fetchData) // Execute the promise function promise := promiseFn() // Wait for result result, _ := promise.Await() fmt.Println(result)
Output: data from database
func PromisifyWithMgr ¶ added in v1.1.4
func PromisifyWithMgr[T any](mgr *PromiseMgr, fn func() (T, error)) func() *Promise[T]
PromisifyWithMgr converts a function that returns (T, error) to a function that returns *Promise[T] This is the most common pattern in Go where functions return (value, error)
func ResetDefaultMgrExecutor ¶ added in v1.1.6
ResetDefaultMgrExecutor resets executor configuration of default manager
func ResetDefaultMgrMicrotask ¶ added in v1.1.6
ResetDefaultMgrMicrotask resets microtask configuration of default manager
Types ¶
type Promise ¶
type Promise[T any] struct { // contains filtered or unexported fields }
func All ¶
All waits for all Promises to complete, rejects if any Promise is rejected
Example ¶
promises := []*Promise[string]{ Resolve("first"), Resolve("second"), Resolve("third"), } results, _ := All(promises...).Await() fmt.Println(results)
Output: [first second third]
func AllSettled ¶
AllSettled waits for all Promises to complete, regardless of success or failure
func Map ¶
Map executes an async function on each element of an array
Example ¶
items := []int{1, 2, 3, 4, 5} // Map each item to a Promise mapPromise := Map(items, func(item int) *Promise[string] { return Delay(fmt.Sprintf("item_%d", item), 10*time.Millisecond) }) results, _ := mapPromise.Await() fmt.Println(results)
Output: [item_1 item_2 item_3 item_4 item_5]
func New ¶
New creates a Promise using the default manager
Example ¶
// Create a new Promise p := New(func(resolve func(string), reject func(error)) { // Simulate async operation resolve("Hello, Promise!") }) // Wait for result result, _ := p.Await() fmt.Println(result)
Output: Hello, Promise!
func NewWithMgr ¶
func NewWithMgr[T any](manager *PromiseMgr, executor func(resolve func(T), reject func(error))) *Promise[T]
NewWithMgr creates a Promise using the specified manager
func Race ¶
Race returns the result of the first completed Promise
Example ¶
fast := Delay("fast", 100*time.Millisecond) slow := Delay("slow", 500*time.Millisecond) result, _ := Race(fast, slow).Await() fmt.Println(result)
Output: fast
func Reduce ¶
Reduce performs async reduction operation on array elements
Example ¶
items := []int{1, 2, 3, 4, 5} // Reduce array with async operations reducePromise := Reduce(items, func(acc int, item int) *Promise[int] { return New(func(resolve func(int), reject func(error)) { time.Sleep(5 * time.Millisecond) resolve(acc + item) }) }, 0) result, _ := reducePromise.Await() fmt.Printf("Sum: %d\n", result)
Output: Sum: 15
func Retry ¶
Retry retries executing a function until success or max retries reached
Example ¶
attempts := 0 fn := func() (string, error) { attempts++ if attempts < 3 { return "", errors.New("temporary failure") } return "success", nil } result, _ := Retry(fn, 3, 10*time.Millisecond).Await() fmt.Printf("Result: %s (attempts: %d)\n", result, attempts)
Output: Result: success (attempts: 3)
func RetryWithContext ¶ added in v1.1.0
func RetryWithContext[T any](ctx context.Context, fn func() (T, error), maxRetries int, delay time.Duration) *Promise[T]
RetryWithContext retries executing a function with context support for cancellation
Example ¶
ExampleRetryWithContext demonstrates retry with context cancellation
attempts := 0 fn := func() (string, error) { attempts++ // Always fail to ensure timeout occurs return "", errors.New("always fails") } // Create context with timeout ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) defer cancel() // Start retry operation result, err := RetryWithContext(ctx, fn, 5, 20*time.Millisecond).Await() if err != nil { fmt.Printf("Retry failed: %v\n", err) } else { fmt.Printf("Result: %s (attempts: %d)\n", result, attempts) }
Output: Retry failed: Retry cancelled during delay: context deadline exceeded
func Timeout ¶
Timeout creates a Promise with timeout
Example ¶
slowPromise := Delay("too slow", 2*time.Second) timeoutPromise := Timeout(slowPromise, 1*time.Second) _, err := timeoutPromise.Await() if err != nil { fmt.Println("Promise timeout") }
Output: Promise timeout
func Try ¶ added in v1.1.6
Try executes a function and returns a Promise that resolves with the result or rejects with any error/panic that occurs during execution This is similar to Node.js's Promise.try()
Example ¶
ExampleTry demonstrates basic usage of Try
// Basic usage promise := Try(func() string { return "Hello, World!" }) result, err := promise.Await() if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Println(result)
Output: Hello, World!
func TryWithError ¶ added in v1.1.6
TryWithError executes a function that returns (T, error) and returns a Promise This is useful for Go functions that follow the standard (value, error) return pattern
Example ¶
ExampleTryWithError demonstrates usage of TryWithError
// With Go's standard error pattern promise := TryWithError(func() (int, error) { // Simulate some operation that might fail if time.Now().Second()%2 == 0 { return 42, nil } return 0, errors.New("operation failed") }) result, err := promise.Await() if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Printf("Result: %d\n", result)
func TryWithErrorAndMgr ¶ added in v1.1.6
func TryWithErrorAndMgr[T any](manager *PromiseMgr, fn func() (T, error)) *Promise[T]
TryWithErrorAndMgr executes a function that returns (T, error) using the specified manager and returns a Promise. This is useful for Go functions that follow the standard (value, error) return pattern
Example ¶
ExampleTryWithErrorAndMgr demonstrates usage of TryWithErrorAndMgr
// Create a custom manager manager := NewPromiseMgr() defer manager.Close() // Use TryWithErrorAndMgr with custom manager promise := TryWithErrorAndMgr(manager, func() (string, error) { return "Success with custom manager!", nil }) result, err := promise.Await() if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Println(result)
Output: Success with custom manager!
func TryWithMgr ¶ added in v1.1.6
func TryWithMgr[T any](manager *PromiseMgr, fn func() T) *Promise[T]
TryWithMgr executes a function using the specified manager and returns a Promise that resolves with the result or rejects with any error/panic that occurs during execution
Example ¶
ExampleTryWithMgr demonstrates usage of TryWithMgr with custom manager
// Create a custom manager manager := NewPromiseMgr() defer manager.Close() // Use TryWithMgr with custom manager promise := TryWithMgr(manager, func() string { return "Hello from custom manager!" }) result, err := promise.Await() if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Println(result)
Output: Hello from custom manager!
func WithResolvers ¶ added in v1.1.2
WithResolvers creates a Promise and returns resolve/reject functions
Example ¶
ExampleWithResolvers demonstrates the WithResolvers function
// Create a Promise with external control promise, resolve, _ := WithResolvers[string]() // Simulate async operation in a goroutine go func() { time.Sleep(100 * time.Millisecond) // Resolve the promise from external code resolve("Hello from WithResolvers!") }() // Wait for result result, _ := promise.Await() fmt.Println(result)
Output: Hello from WithResolvers!
func WithResolversWithMgr ¶ added in v1.1.2
func WithResolversWithMgr[T any](manager *PromiseMgr) (*Promise[T], func(T), func(error))
WithResolversWithMgr creates a Promise with specified manager
Example ¶
ExampleWithResolversWithMgr demonstrates the WithResolversWithMgr function
// Create custom manager manager := NewPromiseMgr() defer manager.Close() // Create a Promise with external control using custom manager promise, resolve, _ := WithResolversWithMgr[string](manager) // Simulate async operation go func() { time.Sleep(50 * time.Millisecond) // Resolve the promise from external code resolve("Hello from custom manager!") }() // Wait for result result, _ := promise.Await() fmt.Println(result)
Output: Hello from custom manager!
func (*Promise[T]) AwaitWithContext ¶
Example ¶
p := New(func(resolve func(string), reject func(error)) { time.Sleep(2 * time.Second) resolve("completed") }) // Create context with timeout ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) defer cancel() // Wait with context _, err := p.AwaitWithContext(ctx) if err != nil { fmt.Println("Context deadline exceeded") }
Output: Context deadline exceeded
func (*Promise[T]) Catch ¶
Example ¶
p := New(func(resolve func(string), reject func(error)) { reject(errors.New("something went wrong")) }) // Handle error result, _ := p.Catch(func(err error) any { return "error handled: " + err.Error() }).Await() fmt.Println(result)
Output: error handled: Promise rejected: something went wrong
func (*Promise[T]) Finally ¶
Example ¶
p := New(func(resolve func(string), reject func(error)) { resolve("success") }) // Always execute cleanup rep := p.Finally(func() { fmt.Println("cleanup completed") }) _, _ = rep.Await()
Output: cleanup completed
func (*Promise[T]) IsFulfilled ¶
func (*Promise[T]) IsRejected ¶
func (*Promise[T]) State ¶
Example ¶
p := New(func(resolve func(string), reject func(error)) { resolve("completed") }) // Check initial state fmt.Printf("Initial state: %v\n", p.State()) // Wait for completion _, _ = p.Await() // Check final state fmt.Printf("Final state: %v\n", p.State())
Output: Initial state: 0 Final state: 1
func (*Promise[T]) Then ¶
Example ¶
p := New(func(resolve func(int), reject func(error)) { resolve(10) }) // Chain promises result := p.Then(func(value int) any { return value * 2 }, nil).Then(func(value any) any { if v, ok := value.(int); ok { return v + 5 } return 0 }, nil) finalResult, _ := result.Await() fmt.Println(finalResult)
Output: 25
type PromiseError ¶ added in v1.1.0
type PromiseError struct { Message string // Human-readable error message Cause error // Original error that caused this Type ErrorType // Type of error Value interface{} // Original panic value (for non-error panics) OriginalError error // Original error being processed (for error callbacks) }
func (*PromiseError) As ¶ added in v1.1.0
func (e *PromiseError) As(target interface{}) bool
As implements error type assertion
func (*PromiseError) Error ¶ added in v1.1.0
func (e *PromiseError) Error() string
Error implements the error interface
func (*PromiseError) Is ¶ added in v1.1.0
func (e *PromiseError) Is(target error) bool
Is implements error comparison
func (*PromiseError) Unwrap ¶ added in v1.1.0
func (e *PromiseError) Unwrap() error
Unwrap returns the cause error for error wrapping
type PromiseMgr ¶
type PromiseMgr struct {
// contains filtered or unexported fields
}
func GetDefaultMgr ¶
func GetDefaultMgr() *PromiseMgr
GetDefaultMgr returns the default Promise manager
Example ¶
// Get current default manager currentMgr := GetDefaultMgr() fmt.Printf("Current workers: %d\n", currentMgr.GetConfig().ExecutorWorkers) // Reset default manager configuration ResetDefaultMgrExecutor(8, 32) ResetDefaultMgrMicrotask(4, 3000) // Get new default manager newMgr := GetDefaultMgr() fmt.Printf("New workers: %d\n", newMgr.GetConfig().ExecutorWorkers) // Verify configuration has been updated config := newMgr.GetConfig() fmt.Printf("New microtask workers: %d\n", config.MicrotaskWorkers) fmt.Printf("New executor workers: %d\n", config.ExecutorWorkers)
func NewPromiseMgr ¶
func NewPromiseMgr() *PromiseMgr
func NewPromiseMgrWithConfig ¶
func NewPromiseMgrWithConfig(config *PromiseMgrConfig) *PromiseMgr
Example ¶
// Create two different managers with different configurations mgr1 := NewPromiseMgrWithConfig(&PromiseMgrConfig{ ExecutorWorkers: 2, ExecutorQueueSize: 8, MicrotaskWorkers: 1, MicrotaskQueueSize: 500, }) mgr2 := NewPromiseMgrWithConfig(&PromiseMgrConfig{ ExecutorWorkers: 4, ExecutorQueueSize: 16, MicrotaskWorkers: 3, MicrotaskQueueSize: 2000, }) // Create Promises using different managers p1 := NewWithMgr(mgr1, func(resolve func(string), reject func(error)) { time.Sleep(10 * time.Millisecond) resolve("from mgr1") }) p2 := NewWithMgr(mgr2, func(resolve func(string), reject func(error)) { time.Sleep(20 * time.Millisecond) resolve("from mgr2") }) // Both Promises can execute in parallel without affecting each other result1, _ := p1.Await() result2, _ := p2.Await() fmt.Printf("Result1: %s\n", result1) fmt.Printf("Result2: %s\n", result2) // Cleanup mgr1.Close() mgr2.Close()
func (*PromiseMgr) GetConfig ¶ added in v1.1.6
func (m *PromiseMgr) GetConfig() *PromiseMgrConfig
GetConfig returns the current configuration
func (*PromiseMgr) IsShutdown ¶
func (m *PromiseMgr) IsShutdown() bool
IsShutdown returns true if the manager is shut down
func (*PromiseMgr) SetExecutorConfig ¶ added in v1.1.6
func (m *PromiseMgr) SetExecutorConfig(workers int, queueSize int) *PromiseMgr
SetExecutorConfig updates executor configuration
func (*PromiseMgr) SetMicrotaskConfig ¶
func (m *PromiseMgr) SetMicrotaskConfig(workers int, queueSize int) *PromiseMgr
SetMicrotaskConfig updates microtask configuration
Example ¶
// Method 1: Configure microtask through global manager GetDefaultMgr().SetMicrotaskConfig(6, 3000) // Method 2: Configure executor worker count through global manager GetDefaultMgr().SetExecutorConfig(8, 32) // Method 3: Create custom manager customMgr := NewPromiseMgrWithConfig(&PromiseMgrConfig{ ExecutorWorkers: 4, ExecutorQueueSize: 16, MicrotaskWorkers: 2, MicrotaskQueueSize: 1000, }) // Create Promise using custom manager p := NewWithMgr(customMgr, func(resolve func(string), reject func(error)) { resolve("Hello from custom manager!") }) // Create Promise using default manager p2 := New(func(resolve func(string), reject func(error)) { resolve("Hello from global manager!") }) fmt.Printf("Custom manager workers: %d\n", customMgr.GetConfig().ExecutorWorkers) fmt.Printf("Global manager workers: %d\n", GetDefaultMgr().GetConfig().ExecutorWorkers) // Wait for Promise completion result1, _ := p.Await() result2, _ := p2.Await() fmt.Printf("Result1: %s\n", result1) fmt.Printf("Result2: %s\n", result2) // Cleanup customMgr.Close()
func (*PromiseMgr) WaitForShutdown ¶ added in v1.1.6
func (m *PromiseMgr) WaitForShutdown()
WaitForShutdown waits for shutdown completion
type PromiseMgrConfig ¶ added in v1.1.6
type PromiseMgrConfig struct { ExecutorWorkers int // Executor worker count ExecutorQueueSize int // Executor queue size MicrotaskWorkers int // Microtask worker count MicrotaskQueueSize int // Microtask queue size }
func DefaultPromiseMgrConfig ¶ added in v1.1.6
func DefaultPromiseMgrConfig() *PromiseMgrConfig