github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/promise.go (about) 1 package utils 2 3 var closedPromiseChan = make(chan struct{}) 4 5 func init() { 6 close(closedPromiseChan) 7 } 8 9 type Promise[T any] struct { 10 Result T 11 Err error 12 done chan struct{} 13 } 14 15 func NewPromise[T any]() *Promise[T] { 16 return &Promise[T]{ 17 done: make(chan struct{}), 18 } 19 } 20 21 func GoPromise[T any](f func() (T, error)) *Promise[T] { 22 p := NewPromise[T]() 23 go func() { p.Resolve(f()) }() 24 return p 25 } 26 27 func NewResolvedPromise[T any](result T, err error) *Promise[T] { 28 return &Promise[T]{ 29 Result: result, 30 Err: err, 31 done: closedPromiseChan, 32 } 33 } 34 35 func (p *Promise[T]) Resolve(result T, err error) { 36 p.Result = result 37 p.Err = err 38 close(p.done) 39 } 40 41 func (p *Promise[T]) Done() <-chan struct{} { 42 return p.done 43 } 44 45 func (p *Promise[T]) Resolved() bool { 46 select { 47 case <-p.done: 48 return true 49 default: 50 return false 51 } 52 }