Documentation
¶
Index ¶
- type Promise
- func MergeAll[T any](ctx context.Context, promises ...*Promise[T]) *Promise[[]T]
- func New[T any](callback func(resolve func(T), reject func(error))) *Promise[T]
- func Reject[T any](err error) *Promise[T]
- func Resolve[T any](value T) *Promise[T]
- func Then[T, U any](ctx context.Context, prom *Promise[T], transformer func(T) *Promise[U]) *Promise[U]
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Promise ¶
type Promise[T any] struct { // contains filtered or unexported fields }
func MergeAll ¶
Merge all promises and return a promise that will return an array of value those values will be the values obtained from promises
Example ¶
jobs := []Job{}
promises := []*promise.Promise[int]{}
for i := 0; i < 10; i++ {
job := Job{
Value1: rand.Intn(10),
Value2: rand.Intn(10),
}
jobs = append(jobs, job)
}
for _, _job := range jobs {
// For new go developers loop variables are loop scoped
// that means that the variable _job is declared only once
// and for each iteration the value is overrited
// that caused a lot of bugs and will be changed in go 1.22
// for more information see https://go.dev/blog/loopvar-preview
job := _job
p := promise.New(func(resolve func(int), reject func(error)) {
result := job.Value1 + job.Value2
resolve(result)
})
promises = append(promises, p)
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
values, err := promise.MergeAll(ctx, promises...).Await(ctx)
if err != nil {
panic(err)
}
fmt.Println(values)
func New ¶
Creates a new promise and exeuctes callback handling a possible panic
Example ¶
p := promise.New(func(resolve func(int), reject func(error)) {
time.Sleep(1 * time.Second)
resolve(1)
})
result, err := p.Await(context.Background())
if err != nil {
panic(err)
}
fmt.Println(result)
Output: 1
func Then ¶ added in v0.2.0
func Then[T, U any](ctx context.Context, prom *Promise[T], transformer func(T) *Promise[U]) *Promise[U]
Then is used to apply a transformation to a promise value returning a new promise with the transformed value. If any error happens then the promise will return an error
Example ¶
p := promise.New(func(resolve func(int), reject func(error)) {
time.Sleep(time.Millisecond * 1)
resolve(1)
})
ctx := context.Background()
newPromise := promise.Then(ctx, p, func(num int) *promise.Promise[string] {
time.Sleep(time.Millisecond * 1)
return promise.Resolve(strconv.Itoa(num * 2))
})
value, err := newPromise.Await(ctx)
if err != nil {
panic(err)
}
fmt.Println(value)
Output: 2
Click to show internal directories.
Click to hide internal directories.