MCPcopy
hub / github.com/duke-git/lancet / All

Function All

promise/promise.go:173–206  ·  view source on GitHub ↗

All resolves when all of the promises have resolved, reject immediately upon any of the input promises rejecting.

(promises []*Promise[T])

Source from the content-addressed store, hash-verified

171
172// All resolves when all of the promises have resolved, reject immediately upon any of the input promises rejecting.
173func All[T any](promises []*Promise[T]) *Promise[[]T] {
174 if len(promises) == 0 {
175 return nil
176 }
177
178 return New(func(resolve func([]T), reject func(error)) {
179 valsChan := make(chan tuple[T, int], len(promises))
180 errsChan := make(chan error, 1)
181
182 for idx, p := range promises {
183 idx := idx
184 _ = Then(p, func(data T) T {
185 valsChan <- tuple[T, int]{_1: data, _2: idx}
186 return data
187 })
188 _ = Catch(p, func(err error) error {
189 errsChan <- err
190 return err
191 })
192 }
193
194 resolutions := make([]T, len(promises))
195 for idx := 0; idx < len(promises); idx++ {
196 select {
197 case val := <-valsChan:
198 resolutions[val._2] = val._1
199 case err := <-errsChan:
200 reject(err)
201 return
202 }
203 }
204 resolve(resolutions)
205 })
206}
207
208// Race will settle the first fullfiled promise among muti promises.
209func Race[T any](promises []*Promise[T]) *Promise[T] {

Callers 2

ExampleAllFunction · 0.85
TestAllFunction · 0.85

Calls 3

ThenFunction · 0.85
CatchFunction · 0.85
NewFunction · 0.70

Tested by 2

ExampleAllFunction · 0.68
TestAllFunction · 0.68