Skip to content

Instantly share code, notes, and snippets.

@matryer
Last active August 17, 2020 02:58
Show Gist options
  • Save matryer/20e2ea821f9df470377084eda6ef0dcb to your computer and use it in GitHub Desktop.
Save matryer/20e2ea821f9df470377084eda6ef0dcb to your computer and use it in GitHub Desktop.
Async helper function for Go.
// Released under MIT License
package main
import "sync"
// asyncFn is a function that can be run asychronously by
// async.
type asyncFn func() error
// async runs many functions at the same time.
// Returns the last not-nil error.
func async(fns ...asyncFn) error {
var errLock sync.Mutex // protects errResult
var errResult error
var wg sync.WaitGroup
wg.Add(len(fns))
for i := range fns {
go func(i int) {
defer wg.Done()
if err := fns[i](); err != nil {
errLock.Lock()
errResult = err
errLock.Unlock()
}
}(i)
}
wg.Wait()
if errResult != nil {
return errResult
}
return nil
}
@earthboundkid
Copy link

I have an errutil.ExecParallel function that is similar, but it relies on errutil.Slice, which can turn a []error into a Multierror. This way you capture all the errors, not just the first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment