v8.run/go/exp@v0.0.26-0.20230226010534-afcdbd3f782d/sync2/runp.go (about)

     1  package sync2
     2  
     3  import "sync"
     4  
     5  func RunParallel[T any](data []T, fn func(T) error) []error {
     6  	var wg sync.WaitGroup
     7  	var errMu sync.Mutex
     8  	var errs []error
     9  
    10  	wg.Add(len(data))
    11  	for i := range data {
    12  		go func(i int) {
    13  			defer wg.Done()
    14  			if err := fn(data[i]); err != nil {
    15  				errMu.Lock()
    16  				errs = append(errs, err)
    17  				errMu.Unlock()
    18  			}
    19  		}(i)
    20  	}
    21  	wg.Wait()
    22  
    23  	return errs
    24  }