Skip to content

Commit 5027bcc

Browse files
committed
Changed buffered channel to slice of channels, because not able to maintain result sequence
1 parent 1ea1193 commit 5027bcc

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

async.go

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,24 @@ type Promise struct {
1818
}
1919

2020
func (p *Promise) All(tasks []Task) Result {
21-
// buffer channels for go routines
22-
workers := make(Channel, len(tasks))
23-
defer close(workers)
21+
// can not use buffer channels, because not able to maintain sequence
22+
// using channel slice
23+
workers := make([]Channel, 0, len(tasks))
2424
for _, task := range tasks {
25-
go func(task Task) {
26-
workers <- task()
27-
}(task)
25+
workers = append(workers, func() Channel {
26+
out := make(Channel)
27+
go func(task Task) {
28+
defer close(out)
29+
out <- task()
30+
}(task)
31+
return out
32+
}())
2833
}
2934

3035
// gather data from all channels
3136
out := make(Result, 0, len(tasks))
32-
for i := 0; i < len(tasks); i++ {
33-
out = append(out, <-workers)
37+
for _, result := range workers {
38+
out = append(out, <-result)
3439
}
3540
return out
3641
}

0 commit comments

Comments
 (0)