go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/promise/race.go (about) 1 package promise 2 3 import "context" 4 5 // Race returns the result of the first promise to resolve. 6 func Race[T any](ctx context.Context, promises ...*Promise[T]) PromiseResult[T] { 7 final := make(chan PromiseResult[T], 1) 8 for index := range promises { 9 go func(i int) { 10 select { 11 case <-ctx.Done(): 12 return 13 case res := <-promises[i].Await(): 14 select { 15 case <-ctx.Done(): 16 return 17 case final <- res: 18 return 19 } 20 } 21 }(index) 22 } 23 24 select { 25 case <-ctx.Done(): 26 return PromiseResult[T]{Err: context.Canceled} 27 case res := <-final: 28 for _, p := range promises { 29 p.Cancel() 30 } 31 return res 32 } 33 }