promise

package module
v1.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 9, 2025 License: MIT Imports: 7 Imported by: 0

README

Go Promise Library

Go Version License

🌍 Multi-language Support: English | 中文

A high-performance, type-safe Go Promise library inspired by JavaScript Promises.

✨ Features

  • 🚀 High Performance: Based on microtask queue, avoiding goroutine leaks
  • 🔒 Type Safe: Using Go generics, compile-time type checking
  • 🛡️ Safe & Reliable: Built-in panic recovery, automatic error propagation
  • 🔄 Chainable: Support Promise chaining operations
  • Concurrency Control: Provide All, Race, Any and other concurrency methods
  • 🎯 Zero Dependencies: Pure Go implementation, no external dependencies
  • 🎛️ Flexible Configuration: Support global and custom Promise managers
  • 🔧 Resource Isolation: Different managers don't affect each other, support independent configuration
  • 🚦 Concurrency Safe: Fixed all data race issues, thread-safe operations

📦 Installation

go get github.com/fupengl/promise

🚀 Quick Start

Basic Usage
package main

import (
    "fmt"
    "github.com/fupengl/promise"
)

func main() {
    // Create a Promise
    p := promise.New(func(resolve func(string), reject func(error)) {
        resolve("Hello, Promise!")
    })

    // Chain operations
    result := p.Then(func(value string) any {
        return value + " World!"
    }, nil)

    // Wait for result
    finalValue, _ := result.Await()
    fmt.Println(finalValue) // Output: Hello, Promise! World!
}
Error Handling
p := promise.New(func(resolve func(int), reject func(error)) {
    reject(errors.New("something went wrong"))
})

result, _ := p.Catch(func(err error) any {
    return 42 // Return default value
}).Await()

fmt.Printf("Result: %v\n", result) // Output: Result: 42
Concurrency Control
// Wait for all Promises to complete
promises := []*promise.Promise[string]{
    promise.Delay("First", 100*time.Millisecond),
    promise.Delay("Second", 200*time.Millisecond),
    promise.Delay("Third", 150*time.Millisecond),
}

results, _ := promise.All(promises...).Await()
fmt.Printf("All completed: %v\n", results)
External Control with WithResolvers
// Create Promise with external control (fastest method)
promise, resolve, reject := promise.WithResolvers[string]()

// Control Promise state from external code
go func() {
    time.Sleep(100 * time.Millisecond)
    resolve("Hello from external control!")
}()

// Wait for result
result, _ := promise.Await()
fmt.Println(result) // Output: Hello from external control!
Converting Go Functions with Promisify
// Convert a function that returns (T, error) to a Promise function
fetchData := func() (string, error) {
    return "data from API", nil
}

// Convert to Promise function
promiseFn := promise.Promisify(fetchData)

// Execute and get result
result, _ := promiseFn().Await()
fmt.Println(result) // Output: data from API

📚 Core API

Constructors
// Create new Promise
func New[T any](executor func(resolve func(T), reject func(error))) *Promise[T]

// Create fulfilled Promise
func Resolve[T any](value T) *Promise[T]

// Create rejected Promise
func Reject[T any](err error) *Promise[T]

// Create Promise with external control (fastest method)
func WithResolvers[T any]() (*Promise[T], func(T), func(error))

// Create Promise with custom manager and external control
func WithResolversWithMgr[T any](manager *PromiseMgr) (*Promise[T], func(T), func(error))
Instance Methods
// Add success/failure handlers
func (p *Promise[T]) Then(onFulfilled func(T) any, onRejected func(error) any) *Promise[any]

// Add error handler
func (p *Promise[T]) Catch(onRejected func(error) any) *Promise[any]

// Add finally handler
func (p *Promise[T]) Finally(onFinally func()) *Promise[T]

// Wait for Promise completion
func (p *Promise[T]) Await() (T, error)

// Wait with context
func (p *Promise[T]) AwaitWithContext(ctx context.Context) (T, error)
Static Methods
// Wait for all Promises to complete
func All[T any](promises ...*Promise[T]) *Promise[[]T]

// Wait for all Promises to complete (regardless of success/failure)
func AllSettled[T any](promises ...*Promise[T]) *Promise[[]Result[T]]

// Return first completed Promise
func Race[T any](promises ...*Promise[T]) *Promise[T]

// Return first successful Promise
func Any[T any](promises ...*Promise[T]) *Promise[T]
Utility Functions
// Delayed Promise
func Delay[T any](value T, delay time.Duration) *Promise[T]

// Timeout control
func Timeout[T any](promise *Promise[T], timeout time.Duration) *Promise[T]

// Retry mechanism
func Retry[T any](fn func() (T, error), maxRetries int, delay time.Duration) *Promise[T]

// Convert (T, error) function to Promise function
func Promisify[T any](fn func() (T, error)) func() *Promise[T]

// Array mapping
func Map[T any, R any](items []T, fn func(T) *Promise[R]) *Promise[[]R]

// Array reduction
func Reduce[T any, R any](items []T, fn func(R, T) *Promise[R], initial R) *Promise[R]

📊 Performance Test Results

Test Environment
  • CPU: Apple M2 Max
  • Go Version: 1.24.2
  • Test Command: go test -bench=. -benchmem
Benchmark Results
BenchmarkPromiseCreation-12              1,278,765 ops    1,013 ns/op    437 B/op    7 allocs/op
BenchmarkPromiseThen-12                  1,918,182 ops      633.1 ns/op    448 B/op    7 allocs/op
BenchmarkPromiseAwait-12                39,064,831 ops      32.87 ns/op      0 B/op    0 allocs/op
BenchmarkMicrotaskQueue-12               3,176,100 ops      370.3 ns/op    134 B/op    2 allocs/op
BenchmarkPromiseChain-12                   171,643 ops   13,399 ns/op    5,096 B/op   72 allocs/op
BenchmarkSimplePromiseChain-12             279,733 ops    6,951 ns/op    2,975 B/op   42 allocs/op
BenchmarkWithResolvers-12                5,637,927 ops      213.1 ns/op    288 B/op    5 allocs/op
BenchmarkWithResolversWithMgr-12         5,736,646 ops      209.4 ns/op    288 B/op    5 allocs/op
BenchmarkResolveMultipleTimes-12         4,016,504 ops      298.4 ns/op    320 B/op    7 allocs/op
BenchmarkRejectMultipleTimes-12          2,891,620 ops      410.3 ns/op    560 B/op   10 allocs/op
BenchmarkMemoryAllocation-12               517,053 ops    2,842 ns/op    1,417 B/op  21 allocs/op
BenchmarkConcurrentPromiseCreation-12     1,000,000 ops    1,201 ns/op      416 B/op    6 allocs/op
BenchmarkTaskPoolReuse-12                1,609,479 ops      758.4 ns/op    440 B/op    8 allocs/op
Performance Analysis
Operation Performance Memory Allocation Description
Promise Creation 1,013 ns/op 437 B/op, 7 allocs/op Basic Promise instance creation
Then Operation 633.1 ns/op 448 B/op, 7 allocs/op Adding Then callback
Promise Await 32.87 ns/op 0 B/op, 0 allocs/op Promise await completion
Microtask Scheduling 370.3 ns/op 134 B/op, 2 allocs/op Microtask queue scheduling
Long Promise Chain (10) 13,399 ns/op 5,096 B/op, 72 allocs/op 10-level Promise chaining
Simple Promise Chain (5) 6,951 ns/op 2,975 B/op, 42 allocs/op 5-level Promise chaining
WithResolvers 213.1 ns/op 288 B/op, 5 allocs/op Fastest Promise creation method
WithResolversWithMgr 209.4 ns/op 288 B/op, 5 allocs/op Fastest with custom manager
Memory Allocation Test 2,842 ns/op 1,417 B/op, 21 allocs/op Complex chaining memory usage
Concurrent Promise Creation 1,201 ns/op 416 B/op, 6 allocs/op Concurrent creation performance
Task Pool Reuse 758.4 ns/op 440 B/op, 8 allocs/op Task object pool reuse effect
Performance Highlights
  • Excellent Promise Await Performance: Only 32.87 nanoseconds, can handle 30 million operations per second
  • Fastest Promise Creation: WithResolversWithMgr achieves 209.4 ns/op, 4.8x faster than traditional creation
  • Efficient Microtask Scheduling: 370.3 nanoseconds scheduling time, suitable for high-frequency async operations
  • Optimized Memory Usage: WithResolvers uses only 288 B/op, 34.1% less memory than traditional creation
  • Smooth Chaining Operations: Each Then operation only takes 633.1 nanoseconds
  • Significant Task Pool Reuse Effect: Performance improvement of about 1.3x through object pool reuse
  • Excellent Concurrent Performance: Stable concurrent creation performance, suitable for high-concurrency scenarios

🧪 Testing

Functional Testing
go test -v
Example Code
go test -v -run Example
Performance Testing
go test -bench=. -benchmem
Race Detection Testing
go test -race -v

🔧 Configuration

Promise Manager Configuration
import "github.com/fupengl/promise"

// Method 1: Configure through global manager
defaultMgr := promise.GetDefaultMgr()
defaultMgr.SetMicrotaskConfig(6, 3000)  // workers, queueSize
defaultMgr.SetExecutorConfig(8, 32)     // workers, queueSize

// Method 2: Create custom manager
customMgr := promise.NewPromiseMgrWithConfig(&promise.PromiseMgrConfig{
    ExecutorWorkers:    4,
    ExecutorQueueSize:  16,
    MicrotaskWorkers:   2,
    MicrotaskQueueSize: 1000,
})

// Create Promise using custom manager
p := promise.NewWithMgr(customMgr, func(resolve func(string), reject func(error)) {
    resolve("Hello from custom manager!")
})

// Cleanup resources
defer customMgr.Close()
Manager API
// Get global default manager
defaultMgr := promise.GetDefaultMgr()

// Configure microtask (workers, queueSize)
defaultMgr.SetMicrotaskConfig(6, 3000)

// Configure executor (workers, queueSize)
defaultMgr.SetExecutorConfig(8, 32)

// Get current configuration
config := defaultMgr.GetConfig()

// Reset default manager configurations
promise.ResetDefaultMgrExecutor(6, 24)      // Reset executor only
promise.ResetDefaultMgrMicrotask(3, 1500)  // Reset microtask only
Configuration Structure
type PromiseMgrConfig struct {
    ExecutorWorkers    int // Number of executor worker goroutines
    ExecutorQueueSize  int // Size of executor task queue
    MicrotaskWorkers   int // Number of microtask worker goroutines
    MicrotaskQueueSize int // Size of microtask queue
}

// Default configuration (automatically calculated based on CPU cores)
func DefaultPromiseMgrConfig() *PromiseMgrConfig

📖 Complete Documentation

🤝 Contributing

Issues and Pull Requests are welcome!

Development Requirements
  • Go 1.21+
  • Go modules support

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

📞 Contact


⭐ If this project helps you, please give us a Star!

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
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

func Promisify[T any](fn func() (T, error)) func() *Promise[T]

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

func ResetDefaultMgrExecutor(workers int, queueSize int)

ResetDefaultMgrExecutor resets executor configuration of default manager

func ResetDefaultMgrMicrotask added in v1.1.6

func ResetDefaultMgrMicrotask(workers int, queueSize int)

ResetDefaultMgrMicrotask resets microtask configuration of default manager

Types

type ErrorType added in v1.1.0

type ErrorType int
const (
	RejectionError ErrorType = iota // Promise rejected
	PanicError                      // Panic occurred in callback
	TimeoutError                    // Promise timeout
	ManagerError                    // Manager-related errors
)

type Promise

type Promise[T any] struct {
	// contains filtered or unexported fields
}

func All

func All[T any](promises ...*Promise[T]) *Promise[[]T]

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

func AllSettled[T any](promises ...*Promise[T]) *Promise[[]Result[T]]

AllSettled waits for all Promises to complete, regardless of success or failure

func Any

func Any[T any](promises ...*Promise[T]) *Promise[T]

Any returns the result of the first successful Promise, rejects if all fail

func Delay

func Delay[T any](value T, delay time.Duration) *Promise[T]

func Map

func Map[T any, R any](items []T, fn func(T) *Promise[R]) *Promise[[]R]

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

func New[T any](executor func(resolve func(T), reject func(error))) *Promise[T]

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

func Race[T any](promises ...*Promise[T]) *Promise[T]

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

func Reduce[T any, R any](items []T, fn func(R, T) *Promise[R], initial R) *Promise[R]

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 Reject

func Reject[T any](err error) *Promise[T]

func Resolve

func Resolve[T any](value T) *Promise[T]

func Retry

func Retry[T any](fn func() (T, error), maxRetries int, delay time.Duration) *Promise[T]

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

func Timeout[T any](promise *Promise[T], timeout time.Duration) *Promise[T]

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

func Try[T any](fn func() T) *Promise[T]

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

func TryWithError[T any](fn func() (T, error)) *Promise[T]

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

func WithResolvers[T any]() (*Promise[T], func(T), func(error))

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]) Await

func (p *Promise[T]) Await() (T, error)

func (*Promise[T]) AwaitWithContext

func (p *Promise[T]) AwaitWithContext(ctx context.Context) (T, error)
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

func (p *Promise[T]) Catch(onRejected func(error) any) *Promise[any]
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

func (p *Promise[T]) Finally(onFinally func()) *Promise[T]
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 (p *Promise[T]) IsFulfilled() bool

func (*Promise[T]) IsPending

func (p *Promise[T]) IsPending() bool

func (*Promise[T]) IsRejected

func (p *Promise[T]) IsRejected() bool

func (*Promise[T]) State

func (p *Promise[T]) State() 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

func (p *Promise[T]) Then(onFulfilled func(T) any, onRejected func(error) any) *Promise[any]
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) Close

func (m *PromiseMgr) Close()

Close shuts down the manager

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

type Result

type Result[T any] struct {
	Value T
	Error error
	Index int
}

type State

type State int
const (
	Pending State = iota
	Fulfilled
	Rejected
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL