Skip to content

Commit

Permalink
feat: add Future
Browse files Browse the repository at this point in the history
  • Loading branch information
moul committed Dec 29, 2020
1 parent f809d12 commit 8cb7ee7
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pattern.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,19 @@ func CheckErr(err error) {
panic(err)
}
}

// Future starts running the given function in background and return a chan that will return the result of the execution.
func Future(fn func() (interface{}, error)) <-chan FutureRet {
c := make(chan FutureRet, 1)
go func() {
ret, err := fn()
c <- FutureRet{Ret: ret, Err: err}
}()
return c
}

// FutureRet is a generic struct returned by Future.
type FutureRet struct {
Ret interface{}
Err error
}
18 changes: 18 additions & 0 deletions pattern_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package u_test
import (
"fmt"
"net/http"
"time"

"moul.io/u"
)
Expand All @@ -19,3 +20,20 @@ func ExampleCheckErr() {
_, err := http.Get("http://foo.bar")
u.CheckErr(err) // panic
}

func ExampleFuture() {
future := u.Future(func() (interface{}, error) {
time.Sleep(100 * time.Millisecond)
return "foobar", nil
})

// here, we can do some stuff

ret := <-future
fmt.Println("Ret:", ret.Ret)
fmt.Println("Err:", ret.Err)

// Output:
// Ret: foobar
// Err: <nil>
}

0 comments on commit 8cb7ee7

Please sign in to comment.