You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
903 B

  1. package util
  2. // initial version comes from https://hackernoon.com/asyncawait-in-golang-an-introductory-guide-ol1e34sg
  3. import "context"
  4. type Future interface {
  5. Await() interface{}
  6. }
  7. type future struct {
  8. await func(ctx context.Context) interface{}
  9. }
  10. func (f future) Await() interface{} {
  11. return f.await(context.Background())
  12. }
  13. type LimitedAsyncExecutor struct {
  14. executor *LimitedConcurrentExecutor
  15. }
  16. func NewLimitedAsyncExecutor(limit int) *LimitedAsyncExecutor {
  17. return &LimitedAsyncExecutor{
  18. executor: NewLimitedConcurrentExecutor(limit),
  19. }
  20. }
  21. func (ae *LimitedAsyncExecutor) Execute(job func() interface{}) Future {
  22. var result interface{}
  23. c := make(chan struct{})
  24. ae.executor.Execute(func() {
  25. defer close(c)
  26. result = job()
  27. })
  28. return future{await: func(ctx context.Context) interface{} {
  29. select {
  30. case <-ctx.Done():
  31. return ctx.Err()
  32. case <-c:
  33. return result
  34. }
  35. }}
  36. }