diff --git a/asyncwait.go b/asyncwait.go index 6101c39..f303c8f 100644 --- a/asyncwait.go +++ b/asyncwait.go @@ -28,18 +28,34 @@ func NewAsyncWait(timeout, pollInterval time.Duration) AsyncWait { } } -// Wait while timeout, make polls every pollInterval for the predicate while is not truth +// Wait while timeout, make polls every pollInterval for the predicate until it returns true func (aw asyncWait) Wait(predicate func() bool) bool { ctx, cancel := context.WithTimeout(context.Background(), aw.timeout) defer cancel() + ticker := time.NewTicker(aw.pollInterval) + defer ticker.Stop() + + runPredicate := func() { + if predicate() { + select { + case aw.doneCh <- struct{}{}: + case <-ctx.Done(): + } + } + } + + // Try to execute predicate immediately + go runPredicate() + + // If the first call was not successful, start polling for { select { case <-aw.doneCh: return true case <-ctx.Done(): return false - case <-time.After(aw.pollInterval): + case <-ticker.C: go func() { if predicate() { select { diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..4908ed9 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/vitalyisaev2/asyncwait + +go 1.16