go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/promise/all.go (about)

     1  package promise
     2  
     3  import "context"
     4  
     5  // All awaits the result of all the promises.
     6  func All[T any](ctx context.Context, promises ...*Promise[T]) (output []PromiseResult[T]) {
     7  	final := make(chan PromiseResult[T], len(promises))
     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  	for x := 0; x < len(promises); x++ {
    24  		select {
    25  		case <-ctx.Done():
    26  			return nil
    27  		case res := <-final:
    28  			output = append(output, res)
    29  		}
    30  	}
    31  	return
    32  }