Skip to content

Commit

Permalink
add async task (#12)
Browse files Browse the repository at this point in the history
  • Loading branch information
hoanguyenkh authored Nov 15, 2024
1 parent 91bfb59 commit b6619e2
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 16 deletions.
26 changes: 10 additions & 16 deletions example/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ package main
import (
"context"
"fmt"
"github.com/hoanguyenkh/promise4g"
"time"

"github.com/hoanguyenkh/promise4g"
)

type httpResponse1 struct {
Expand Down Expand Up @@ -37,24 +38,14 @@ func fakeHttp2(url string) (httpResponse2, error) {

func main() {
ctx := context.Background()
p1 := promise4g.New(func(resolve func(any), reject func(error)) {
resp1, err := fakeHttp1("fakeHttp1")
if err != nil {
reject(err)
} else {
resolve(resp1)
}
t1 := time.Now()
p1 := promise4g.AsyncTask(func() (any, error) {
return fakeHttp1("fakeHttp1")
})

p2 := promise4g.New(func(resolve func(any), reject func(error)) {
resp1, err := fakeHttp2("fakeHttp2")
if err != nil {
reject(err)
} else {
resolve(resp1)
}
p2 := promise4g.AsyncTask(func() (any, error) {
return fakeHttp2("fakeHttp2")
})

p := promise4g.All(ctx, p1, p2)
results, err := p.Await(ctx)
if err != nil {
Expand All @@ -65,4 +56,7 @@ func main() {
res2 := results[1].(httpResponse2)
fmt.Println(res1.RequestId, res1.Message)
fmt.Println(res2.RequestId, res2.Username)

fmt.Println("total time: ", time.Since(t1))

}
13 changes: 13 additions & 0 deletions promise.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,16 @@ func Timeout[T any](p *Promise[T], d time.Duration) *Promise[T] {
}
}, defaultPool)
}

// AsyncTask creates a new Promise that executes the provided function asynchronously.
// It resolves with the function's result or rejects with an error if the function fails.
func AsyncTask[T any](fn func() (T, error)) *Promise[T] {
return New(func(resolve func(T), reject func(error)) {
resp, err := fn()
if err != nil {
reject(err)
} else {
resolve(resp)
}
})
}

0 comments on commit b6619e2

Please sign in to comment.