Last active
August 17, 2020 02:58
-
-
Save matryer/20e2ea821f9df470377084eda6ef0dcb to your computer and use it in GitHub Desktop.
Async helper function for Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.