-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request samber#86 from CorentinClabaut/async
Implements Async
- Loading branch information
Showing
3 changed files
with
55 additions
and
2 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
package lo | ||
|
||
// Async executes a function in a goroutine and returns the result in a channel. | ||
func Async[T any](f func() T) chan T { | ||
ch := make(chan T) | ||
go func() { | ||
ch <- f() | ||
}() | ||
return ch | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package lo | ||
|
||
import ( | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestAsync(t *testing.T) { | ||
is := assert.New(t) | ||
|
||
sync := make(chan struct{}) | ||
|
||
ch := Async(func() int { | ||
<-sync | ||
return 10 | ||
}) | ||
|
||
sync <- struct{}{} | ||
|
||
select { | ||
case result := <-ch: | ||
is.Equal(result, 10) | ||
case <-time.After(time.Millisecond): | ||
is.Fail("Async should not block") | ||
} | ||
} |